| 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 | |
| 9 | #include "llvm/Bitcode/BitcodeReader.h" |
| 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" |
| 17 | #include "llvm/ADT/SmallString.h" |
| 18 | #include "llvm/ADT/SmallVector.h" |
| 19 | #include "llvm/ADT/StringRef.h" |
| 20 | #include "llvm/ADT/Twine.h" |
| 21 | #include "llvm/Bitcode/BitcodeCommon.h" |
| 22 | #include "llvm/Bitcode/LLVMBitCodes.h" |
| 23 | #include "llvm/Bitstream/BitstreamReader.h" |
| 24 | #include "llvm/Config/llvm-config.h" |
| 25 | #include "llvm/IR/Argument.h" |
| 26 | #include "llvm/IR/AttributeMask.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" |
| 33 | #include "llvm/IR/ConstantRangeList.h" |
| 34 | #include "llvm/IR/Constants.h" |
| 35 | #include "llvm/IR/DataLayout.h" |
| 36 | #include "llvm/IR/DebugInfo.h" |
| 37 | #include "llvm/IR/DebugInfoMetadata.h" |
| 38 | #include "llvm/IR/DebugLoc.h" |
| 39 | #include "llvm/IR/DerivedTypes.h" |
| 40 | #include "llvm/IR/Function.h" |
| 41 | #include "llvm/IR/GVMaterializer.h" |
| 42 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
| 43 | #include "llvm/IR/GlobalAlias.h" |
| 44 | #include "llvm/IR/GlobalIFunc.h" |
| 45 | #include "llvm/IR/GlobalObject.h" |
| 46 | #include "llvm/IR/GlobalValue.h" |
| 47 | #include "llvm/IR/GlobalVariable.h" |
| 48 | #include "llvm/IR/InlineAsm.h" |
| 49 | #include "llvm/IR/InstIterator.h" |
| 50 | #include "llvm/IR/InstrTypes.h" |
| 51 | #include "llvm/IR/Instruction.h" |
| 52 | #include "llvm/IR/Instructions.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" |
| 59 | #include "llvm/IR/ModuleSummaryIndex.h" |
| 60 | #include "llvm/IR/Operator.h" |
| 61 | #include "llvm/IR/ProfDataUtils.h" |
| 62 | #include "llvm/IR/Type.h" |
| 63 | #include "llvm/IR/Value.h" |
| 64 | #include "llvm/IR/Verifier.h" |
| 65 | #include "llvm/Support/AtomicOrdering.h" |
| 66 | #include "llvm/Support/Casting.h" |
| 67 | #include "llvm/Support/CommandLine.h" |
| 68 | #include "llvm/Support/Compiler.h" |
| 69 | #include "llvm/Support/Debug.h" |
| 70 | #include "llvm/Support/Error.h" |
| 71 | #include "llvm/Support/ErrorHandling.h" |
| 72 | #include "llvm/Support/ErrorOr.h" |
| 73 | #include "llvm/Support/MathExtras.h" |
| 74 | #include "llvm/Support/MemoryBuffer.h" |
| 75 | #include "llvm/Support/ModRef.h" |
| 76 | #include "llvm/Support/raw_ostream.h" |
| 77 | #include "llvm/TargetParser/Triple.h" |
| 78 | #include <algorithm> |
| 79 | #include <cassert> |
| 80 | #include <cstddef> |
| 81 | #include <cstdint> |
| 82 | #include <deque> |
| 83 | #include <map> |
| 84 | #include <memory> |
| 85 | #include <optional> |
| 86 | #include <string> |
| 87 | #include <system_error> |
| 88 | #include <tuple> |
| 89 | #include <utility> |
| 90 | #include <vector> |
| 91 | |
| 92 | using namespace llvm; |
| 93 | |
| 94 | static cl::opt<bool> PrintSummaryGUIDs( |
| 95 | "print-summary-global-ids" , cl::init(Val: false), cl::Hidden, |
| 96 | cl::desc( |
| 97 | "Print the global id for each value when reading the module summary" )); |
| 98 | |
| 99 | static cl::opt<bool> ExpandConstantExprs( |
| 100 | "expand-constant-exprs" , cl::Hidden, |
| 101 | cl::desc( |
| 102 | "Expand constant expressions to instructions for testing purposes" )); |
| 103 | |
| 104 | namespace { |
| 105 | |
| 106 | enum { |
| 107 | SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex |
| 108 | }; |
| 109 | |
| 110 | } // end anonymous namespace |
| 111 | |
| 112 | static Error error(const Twine &Message) { |
| 113 | return make_error<StringError>( |
| 114 | Args: Message, Args: make_error_code(E: BitcodeError::CorruptedBitcode)); |
| 115 | } |
| 116 | |
| 117 | static Error (BitstreamCursor &Stream) { |
| 118 | if (!Stream.canSkipToPos(pos: 4)) |
| 119 | return createStringError(EC: std::errc::illegal_byte_sequence, |
| 120 | Fmt: "file too small to contain bitcode header" ); |
| 121 | for (unsigned C : {'B', 'C'}) |
| 122 | if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(NumBits: 8)) { |
| 123 | if (Res.get() != C) |
| 124 | return createStringError(EC: std::errc::illegal_byte_sequence, |
| 125 | Fmt: "file doesn't start with bitcode header" ); |
| 126 | } else |
| 127 | return Res.takeError(); |
| 128 | for (unsigned C : {0x0, 0xC, 0xE, 0xD}) |
| 129 | if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(NumBits: 4)) { |
| 130 | if (Res.get() != C) |
| 131 | return createStringError(EC: std::errc::illegal_byte_sequence, |
| 132 | Fmt: "file doesn't start with bitcode header" ); |
| 133 | } else |
| 134 | return Res.takeError(); |
| 135 | return Error::success(); |
| 136 | } |
| 137 | |
| 138 | static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { |
| 139 | const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); |
| 140 | const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); |
| 141 | |
| 142 | if (Buffer.getBufferSize() & 3) |
| 143 | return error(Message: "Invalid bitcode signature" ); |
| 144 | |
| 145 | // If we have a wrapper header, parse it and ignore the non-bc file contents. |
| 146 | // The magic number is 0x0B17C0DE stored in little endian. |
| 147 | if (isBitcodeWrapper(BufPtr, BufEnd)) |
| 148 | if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, VerifyBufferSize: true)) |
| 149 | return error(Message: "Invalid bitcode wrapper header" ); |
| 150 | |
| 151 | BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); |
| 152 | if (Error Err = hasInvalidBitcodeHeader(Stream)) |
| 153 | return std::move(Err); |
| 154 | |
| 155 | return std::move(Stream); |
| 156 | } |
| 157 | |
| 158 | /// Convert a string from a record into an std::string, return true on failure. |
| 159 | template <typename StrTy> |
| 160 | static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, |
| 161 | StrTy &Result) { |
| 162 | if (Idx > Record.size()) |
| 163 | return true; |
| 164 | |
| 165 | Result.append(Record.begin() + Idx, Record.end()); |
| 166 | return false; |
| 167 | } |
| 168 | |
| 169 | // Strip all the TBAA attachment for the module. |
| 170 | static void stripTBAA(Module *M) { |
| 171 | for (auto &F : *M) { |
| 172 | if (F.isMaterializable()) |
| 173 | continue; |
| 174 | for (auto &I : instructions(F)) |
| 175 | I.setMetadata(KindID: LLVMContext::MD_tbaa, Node: nullptr); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the |
| 180 | /// "epoch" encoded in the bitcode, and return the producer name if any. |
| 181 | static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { |
| 182 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::IDENTIFICATION_BLOCK_ID)) |
| 183 | return std::move(Err); |
| 184 | |
| 185 | // Read all the records. |
| 186 | SmallVector<uint64_t, 64> Record; |
| 187 | |
| 188 | std::string ProducerIdentification; |
| 189 | |
| 190 | while (true) { |
| 191 | BitstreamEntry Entry; |
| 192 | if (Error E = Stream.advance().moveInto(Value&: Entry)) |
| 193 | return std::move(E); |
| 194 | |
| 195 | switch (Entry.Kind) { |
| 196 | default: |
| 197 | case BitstreamEntry::Error: |
| 198 | return error(Message: "Malformed block" ); |
| 199 | case BitstreamEntry::EndBlock: |
| 200 | return ProducerIdentification; |
| 201 | case BitstreamEntry::Record: |
| 202 | // The interesting case. |
| 203 | break; |
| 204 | } |
| 205 | |
| 206 | // Read a record. |
| 207 | Record.clear(); |
| 208 | Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 209 | if (!MaybeBitCode) |
| 210 | return MaybeBitCode.takeError(); |
| 211 | switch (MaybeBitCode.get()) { |
| 212 | default: // Default behavior: reject |
| 213 | return error(Message: "Invalid value" ); |
| 214 | case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] |
| 215 | convertToString(Record, Idx: 0, Result&: ProducerIdentification); |
| 216 | break; |
| 217 | case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] |
| 218 | unsigned epoch = (unsigned)Record[0]; |
| 219 | if (epoch != bitc::BITCODE_CURRENT_EPOCH) { |
| 220 | return error( |
| 221 | Message: Twine("Incompatible epoch: Bitcode '" ) + Twine(epoch) + |
| 222 | "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'" ); |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { |
| 230 | // We expect a number of well-defined blocks, though we don't necessarily |
| 231 | // need to understand them all. |
| 232 | while (true) { |
| 233 | if (Stream.AtEndOfStream()) |
| 234 | return "" ; |
| 235 | |
| 236 | BitstreamEntry Entry; |
| 237 | if (Error E = Stream.advance().moveInto(Value&: Entry)) |
| 238 | return std::move(E); |
| 239 | |
| 240 | switch (Entry.Kind) { |
| 241 | case BitstreamEntry::EndBlock: |
| 242 | case BitstreamEntry::Error: |
| 243 | return error(Message: "Malformed block" ); |
| 244 | |
| 245 | case BitstreamEntry::SubBlock: |
| 246 | if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) |
| 247 | return readIdentificationBlock(Stream); |
| 248 | |
| 249 | // Ignore other sub-blocks. |
| 250 | if (Error Err = Stream.SkipBlock()) |
| 251 | return std::move(Err); |
| 252 | continue; |
| 253 | case BitstreamEntry::Record: |
| 254 | if (Error E = Stream.skipRecord(AbbrevID: Entry.ID).takeError()) |
| 255 | return std::move(E); |
| 256 | continue; |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { |
| 262 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID)) |
| 263 | return std::move(Err); |
| 264 | |
| 265 | SmallVector<uint64_t, 64> Record; |
| 266 | // Read all the records for this module. |
| 267 | |
| 268 | while (true) { |
| 269 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 270 | if (!MaybeEntry) |
| 271 | return MaybeEntry.takeError(); |
| 272 | BitstreamEntry Entry = MaybeEntry.get(); |
| 273 | |
| 274 | switch (Entry.Kind) { |
| 275 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 276 | case BitstreamEntry::Error: |
| 277 | return error(Message: "Malformed block" ); |
| 278 | case BitstreamEntry::EndBlock: |
| 279 | return false; |
| 280 | case BitstreamEntry::Record: |
| 281 | // The interesting case. |
| 282 | break; |
| 283 | } |
| 284 | |
| 285 | // Read a record. |
| 286 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 287 | if (!MaybeRecord) |
| 288 | return MaybeRecord.takeError(); |
| 289 | switch (MaybeRecord.get()) { |
| 290 | default: |
| 291 | break; // Default behavior, ignore unknown content. |
| 292 | case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] |
| 293 | std::string S; |
| 294 | if (convertToString(Record, Idx: 0, Result&: S)) |
| 295 | return error(Message: "Invalid section name record" ); |
| 296 | // Check for the i386 and other (x86_64, ARM) conventions |
| 297 | if (S.find(s: "__DATA,__objc_catlist" ) != std::string::npos || |
| 298 | S.find(s: "__OBJC,__category" ) != std::string::npos || |
| 299 | S.find(s: "__TEXT,__swift" ) != std::string::npos) |
| 300 | return true; |
| 301 | break; |
| 302 | } |
| 303 | } |
| 304 | Record.clear(); |
| 305 | } |
| 306 | llvm_unreachable("Exit infinite loop" ); |
| 307 | } |
| 308 | |
| 309 | static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { |
| 310 | // We expect a number of well-defined blocks, though we don't necessarily |
| 311 | // need to understand them all. |
| 312 | while (true) { |
| 313 | BitstreamEntry Entry; |
| 314 | if (Error E = Stream.advance().moveInto(Value&: Entry)) |
| 315 | return std::move(E); |
| 316 | |
| 317 | switch (Entry.Kind) { |
| 318 | case BitstreamEntry::Error: |
| 319 | return error(Message: "Malformed block" ); |
| 320 | case BitstreamEntry::EndBlock: |
| 321 | return false; |
| 322 | |
| 323 | case BitstreamEntry::SubBlock: |
| 324 | if (Entry.ID == bitc::MODULE_BLOCK_ID) |
| 325 | return hasObjCCategoryInModule(Stream); |
| 326 | |
| 327 | // Ignore other sub-blocks. |
| 328 | if (Error Err = Stream.SkipBlock()) |
| 329 | return std::move(Err); |
| 330 | continue; |
| 331 | |
| 332 | case BitstreamEntry::Record: |
| 333 | if (Error E = Stream.skipRecord(AbbrevID: Entry.ID).takeError()) |
| 334 | return std::move(E); |
| 335 | continue; |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { |
| 341 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID)) |
| 342 | return std::move(Err); |
| 343 | |
| 344 | SmallVector<uint64_t, 64> Record; |
| 345 | |
| 346 | std::string Triple; |
| 347 | |
| 348 | // Read all the records for this module. |
| 349 | while (true) { |
| 350 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 351 | if (!MaybeEntry) |
| 352 | return MaybeEntry.takeError(); |
| 353 | BitstreamEntry Entry = MaybeEntry.get(); |
| 354 | |
| 355 | switch (Entry.Kind) { |
| 356 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 357 | case BitstreamEntry::Error: |
| 358 | return error(Message: "Malformed block" ); |
| 359 | case BitstreamEntry::EndBlock: |
| 360 | return Triple; |
| 361 | case BitstreamEntry::Record: |
| 362 | // The interesting case. |
| 363 | break; |
| 364 | } |
| 365 | |
| 366 | // Read a record. |
| 367 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 368 | if (!MaybeRecord) |
| 369 | return MaybeRecord.takeError(); |
| 370 | switch (MaybeRecord.get()) { |
| 371 | default: break; // Default behavior, ignore unknown content. |
| 372 | case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] |
| 373 | std::string S; |
| 374 | if (convertToString(Record, Idx: 0, Result&: S)) |
| 375 | return error(Message: "Invalid triple record" ); |
| 376 | Triple = S; |
| 377 | break; |
| 378 | } |
| 379 | } |
| 380 | Record.clear(); |
| 381 | } |
| 382 | llvm_unreachable("Exit infinite loop" ); |
| 383 | } |
| 384 | |
| 385 | static Expected<std::string> readTriple(BitstreamCursor &Stream) { |
| 386 | // We expect a number of well-defined blocks, though we don't necessarily |
| 387 | // need to understand them all. |
| 388 | while (true) { |
| 389 | Expected<BitstreamEntry> MaybeEntry = Stream.advance(); |
| 390 | if (!MaybeEntry) |
| 391 | return MaybeEntry.takeError(); |
| 392 | BitstreamEntry Entry = MaybeEntry.get(); |
| 393 | |
| 394 | switch (Entry.Kind) { |
| 395 | case BitstreamEntry::Error: |
| 396 | return error(Message: "Malformed block" ); |
| 397 | case BitstreamEntry::EndBlock: |
| 398 | return "" ; |
| 399 | |
| 400 | case BitstreamEntry::SubBlock: |
| 401 | if (Entry.ID == bitc::MODULE_BLOCK_ID) |
| 402 | return readModuleTriple(Stream); |
| 403 | |
| 404 | // Ignore other sub-blocks. |
| 405 | if (Error Err = Stream.SkipBlock()) |
| 406 | return std::move(Err); |
| 407 | continue; |
| 408 | |
| 409 | case BitstreamEntry::Record: |
| 410 | if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(AbbrevID: Entry.ID)) |
| 411 | continue; |
| 412 | else |
| 413 | return Skipped.takeError(); |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | namespace { |
| 419 | |
| 420 | class BitcodeReaderBase { |
| 421 | protected: |
| 422 | BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) |
| 423 | : Stream(std::move(Stream)), Strtab(Strtab) { |
| 424 | this->Stream.setBlockInfo(&BlockInfo); |
| 425 | } |
| 426 | |
| 427 | BitstreamBlockInfo BlockInfo; |
| 428 | BitstreamCursor Stream; |
| 429 | StringRef Strtab; |
| 430 | |
| 431 | /// In version 2 of the bitcode we store names of global values and comdats in |
| 432 | /// a string table rather than in the VST. |
| 433 | bool UseStrtab = false; |
| 434 | |
| 435 | Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); |
| 436 | |
| 437 | /// If this module uses a string table, pop the reference to the string table |
| 438 | /// and return the referenced string and the rest of the record. Otherwise |
| 439 | /// just return the record itself. |
| 440 | std::pair<StringRef, ArrayRef<uint64_t>> |
| 441 | readNameFromStrtab(ArrayRef<uint64_t> Record); |
| 442 | |
| 443 | Error readBlockInfo(); |
| 444 | |
| 445 | // Contains an arbitrary and optional string identifying the bitcode producer |
| 446 | std::string ProducerIdentification; |
| 447 | |
| 448 | Error error(const Twine &Message); |
| 449 | }; |
| 450 | |
| 451 | } // end anonymous namespace |
| 452 | |
| 453 | Error BitcodeReaderBase::error(const Twine &Message) { |
| 454 | std::string FullMsg = Message.str(); |
| 455 | if (!ProducerIdentification.empty()) |
| 456 | FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + |
| 457 | LLVM_VERSION_STRING "')" ; |
| 458 | return ::error(Message: FullMsg); |
| 459 | } |
| 460 | |
| 461 | Expected<unsigned> |
| 462 | BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { |
| 463 | if (Record.empty()) |
| 464 | return error(Message: "Invalid version record" ); |
| 465 | unsigned ModuleVersion = Record[0]; |
| 466 | if (ModuleVersion > 2) |
| 467 | return error(Message: "Invalid value" ); |
| 468 | UseStrtab = ModuleVersion >= 2; |
| 469 | return ModuleVersion; |
| 470 | } |
| 471 | |
| 472 | std::pair<StringRef, ArrayRef<uint64_t>> |
| 473 | BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { |
| 474 | if (!UseStrtab) |
| 475 | return {"" , Record}; |
| 476 | // Invalid reference. Let the caller complain about the record being empty. |
| 477 | if (Record[0] + Record[1] > Strtab.size()) |
| 478 | return {"" , {}}; |
| 479 | return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(N: 2)}; |
| 480 | } |
| 481 | |
| 482 | namespace { |
| 483 | |
| 484 | /// This represents a constant expression or constant aggregate using a custom |
| 485 | /// structure internal to the bitcode reader. Later, this structure will be |
| 486 | /// expanded by materializeValue() either into a constant expression/aggregate, |
| 487 | /// or into an instruction sequence at the point of use. This allows us to |
| 488 | /// upgrade bitcode using constant expressions even if this kind of constant |
| 489 | /// expression is no longer supported. |
| 490 | class BitcodeConstant final : public Value, |
| 491 | TrailingObjects<BitcodeConstant, unsigned> { |
| 492 | friend TrailingObjects; |
| 493 | |
| 494 | // Value subclass ID: Pick largest possible value to avoid any clashes. |
| 495 | static constexpr uint8_t SubclassID = 255; |
| 496 | |
| 497 | public: |
| 498 | // Opcodes used for non-expressions. This includes constant aggregates |
| 499 | // (struct, array, vector) that might need expansion, as well as non-leaf |
| 500 | // constants that don't need expansion (no_cfi, dso_local, blockaddress), |
| 501 | // but still go through BitcodeConstant to avoid different uselist orders |
| 502 | // between the two cases. |
| 503 | static constexpr uint8_t ConstantStructOpcode = 255; |
| 504 | static constexpr uint8_t ConstantArrayOpcode = 254; |
| 505 | static constexpr uint8_t ConstantVectorOpcode = 253; |
| 506 | static constexpr uint8_t NoCFIOpcode = 252; |
| 507 | static constexpr uint8_t DSOLocalEquivalentOpcode = 251; |
| 508 | static constexpr uint8_t BlockAddressOpcode = 250; |
| 509 | static constexpr uint8_t ConstantPtrAuthOpcode = 249; |
| 510 | static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode; |
| 511 | |
| 512 | // Separate struct to make passing different number of parameters to |
| 513 | // BitcodeConstant::create() more convenient. |
| 514 | struct { |
| 515 | uint8_t ; |
| 516 | uint8_t ; |
| 517 | unsigned = 0; |
| 518 | Type * = nullptr; |
| 519 | std::optional<ConstantRange> ; |
| 520 | |
| 521 | (uint8_t Opcode, uint8_t Flags = 0, Type *SrcElemTy = nullptr, |
| 522 | std::optional<ConstantRange> InRange = std::nullopt) |
| 523 | : Opcode(Opcode), Flags(Flags), SrcElemTy(SrcElemTy), |
| 524 | InRange(std::move(InRange)) {} |
| 525 | |
| 526 | (uint8_t Opcode, uint8_t Flags, unsigned BlockAddressBB) |
| 527 | : Opcode(Opcode), Flags(Flags), BlockAddressBB(BlockAddressBB) {} |
| 528 | }; |
| 529 | |
| 530 | uint8_t Opcode; |
| 531 | uint8_t Flags; |
| 532 | unsigned NumOperands; |
| 533 | unsigned BlockAddressBB; |
| 534 | Type *SrcElemTy; // GEP source element type. |
| 535 | std::optional<ConstantRange> InRange; // GEP inrange attribute. |
| 536 | |
| 537 | private: |
| 538 | (Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs) |
| 539 | : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags), |
| 540 | NumOperands(OpIDs.size()), BlockAddressBB(Info.BlockAddressBB), |
| 541 | SrcElemTy(Info.SrcElemTy), InRange(Info.InRange) { |
| 542 | llvm::uninitialized_copy(Src&: OpIDs, Dst: getTrailingObjects()); |
| 543 | } |
| 544 | |
| 545 | BitcodeConstant &operator=(const BitcodeConstant &) = delete; |
| 546 | |
| 547 | public: |
| 548 | static BitcodeConstant *(BumpPtrAllocator &A, Type *Ty, |
| 549 | const ExtraInfo &Info, |
| 550 | ArrayRef<unsigned> OpIDs) { |
| 551 | void *Mem = A.Allocate(Size: totalSizeToAlloc<unsigned>(Counts: OpIDs.size()), |
| 552 | Alignment: alignof(BitcodeConstant)); |
| 553 | return new (Mem) BitcodeConstant(Ty, Info, OpIDs); |
| 554 | } |
| 555 | |
| 556 | static bool classof(const Value *V) { return V->getValueID() == SubclassID; } |
| 557 | |
| 558 | ArrayRef<unsigned> getOperandIDs() const { |
| 559 | return ArrayRef(getTrailingObjects(), NumOperands); |
| 560 | } |
| 561 | |
| 562 | std::optional<ConstantRange> getInRange() const { |
| 563 | assert(Opcode == Instruction::GetElementPtr); |
| 564 | return InRange; |
| 565 | } |
| 566 | |
| 567 | const char *getOpcodeName() const { |
| 568 | return Instruction::getOpcodeName(Opcode); |
| 569 | } |
| 570 | }; |
| 571 | |
| 572 | class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { |
| 573 | LLVMContext &Context; |
| 574 | Module *TheModule = nullptr; |
| 575 | // Next offset to start scanning for lazy parsing of function bodies. |
| 576 | uint64_t NextUnreadBit = 0; |
| 577 | // Last function offset found in the VST. |
| 578 | uint64_t LastFunctionBlockBit = 0; |
| 579 | bool SeenValueSymbolTable = false; |
| 580 | uint64_t VSTOffset = 0; |
| 581 | |
| 582 | std::vector<std::string> SectionTable; |
| 583 | std::vector<std::string> GCTable; |
| 584 | |
| 585 | std::vector<Type *> TypeList; |
| 586 | /// Track type IDs of contained types. Order is the same as the contained |
| 587 | /// types of a Type*. This is used during upgrades of typed pointer IR in |
| 588 | /// opaque pointer mode. |
| 589 | DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs; |
| 590 | /// In some cases, we need to create a type ID for a type that was not |
| 591 | /// explicitly encoded in the bitcode, or we don't know about at the current |
| 592 | /// point. For example, a global may explicitly encode the value type ID, but |
| 593 | /// not have a type ID for the pointer to value type, for which we create a |
| 594 | /// virtual type ID instead. This map stores the new type ID that was created |
| 595 | /// for the given pair of Type and contained type ID. |
| 596 | DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs; |
| 597 | DenseMap<Function *, unsigned> FunctionTypeIDs; |
| 598 | /// Allocator for BitcodeConstants. This should come before ValueList, |
| 599 | /// because the ValueList might hold ValueHandles to these constants, so |
| 600 | /// ValueList must be destroyed before Alloc. |
| 601 | BumpPtrAllocator Alloc; |
| 602 | BitcodeReaderValueList ValueList; |
| 603 | std::optional<MetadataLoader> MDLoader; |
| 604 | std::vector<Comdat *> ComdatList; |
| 605 | DenseSet<GlobalObject *> ImplicitComdatObjects; |
| 606 | SmallVector<Instruction *, 64> InstructionList; |
| 607 | |
| 608 | std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; |
| 609 | std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits; |
| 610 | |
| 611 | struct FunctionOperandInfo { |
| 612 | Function *F; |
| 613 | unsigned PersonalityFn; |
| 614 | unsigned Prefix; |
| 615 | unsigned Prologue; |
| 616 | }; |
| 617 | std::vector<FunctionOperandInfo> FunctionOperands; |
| 618 | |
| 619 | /// The set of attributes by index. Index zero in the file is for null, and |
| 620 | /// is thus not represented here. As such all indices are off by one. |
| 621 | std::vector<AttributeList> MAttributes; |
| 622 | |
| 623 | /// The set of attribute groups. |
| 624 | std::map<unsigned, AttributeList> MAttributeGroups; |
| 625 | |
| 626 | /// While parsing a function body, this is a list of the basic blocks for the |
| 627 | /// function. |
| 628 | std::vector<BasicBlock*> FunctionBBs; |
| 629 | |
| 630 | // When reading the module header, this list is populated with functions that |
| 631 | // have bodies later in the file. |
| 632 | std::vector<Function*> FunctionsWithBodies; |
| 633 | |
| 634 | // When intrinsic functions are encountered which require upgrading they are |
| 635 | // stored here with their replacement function. |
| 636 | using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; |
| 637 | UpdatedIntrinsicMap UpgradedIntrinsics; |
| 638 | |
| 639 | // Several operations happen after the module header has been read, but |
| 640 | // before function bodies are processed. This keeps track of whether |
| 641 | // we've done this yet. |
| 642 | bool SeenFirstFunctionBody = false; |
| 643 | |
| 644 | /// When function bodies are initially scanned, this map contains info about |
| 645 | /// where to find deferred function body in the stream. |
| 646 | DenseMap<Function*, uint64_t> DeferredFunctionInfo; |
| 647 | |
| 648 | /// When Metadata block is initially scanned when parsing the module, we may |
| 649 | /// choose to defer parsing of the metadata. This vector contains info about |
| 650 | /// which Metadata blocks are deferred. |
| 651 | std::vector<uint64_t> DeferredMetadataInfo; |
| 652 | |
| 653 | /// These are basic blocks forward-referenced by block addresses. They are |
| 654 | /// inserted lazily into functions when they're loaded. The basic block ID is |
| 655 | /// its index into the vector. |
| 656 | DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; |
| 657 | std::deque<Function *> BasicBlockFwdRefQueue; |
| 658 | |
| 659 | /// These are Functions that contain BlockAddresses which refer a different |
| 660 | /// Function. When parsing the different Function, queue Functions that refer |
| 661 | /// to the different Function. Those Functions must be materialized in order |
| 662 | /// to resolve their BlockAddress constants before the different Function |
| 663 | /// gets moved into another Module. |
| 664 | std::vector<Function *> BackwardRefFunctions; |
| 665 | |
| 666 | /// Indicates that we are using a new encoding for instruction operands where |
| 667 | /// most operands in the current FUNCTION_BLOCK are encoded relative to the |
| 668 | /// instruction number, for a more compact encoding. Some instruction |
| 669 | /// operands are not relative to the instruction ID: basic block numbers, and |
| 670 | /// types. Once the old style function blocks have been phased out, we would |
| 671 | /// not need this flag. |
| 672 | bool UseRelativeIDs = false; |
| 673 | |
| 674 | /// True if all functions will be materialized, negating the need to process |
| 675 | /// (e.g.) blockaddress forward references. |
| 676 | bool WillMaterializeAllForwardRefs = false; |
| 677 | |
| 678 | /// Tracks whether we have seen debug intrinsics or records in this bitcode; |
| 679 | /// seeing both in a single module is currently a fatal error. |
| 680 | bool SeenDebugIntrinsic = false; |
| 681 | bool SeenDebugRecord = false; |
| 682 | |
| 683 | bool StripDebugInfo = false; |
| 684 | TBAAVerifier TBAAVerifyHelper; |
| 685 | |
| 686 | std::vector<std::string> BundleTags; |
| 687 | SmallVector<SyncScope::ID, 8> SSIDs; |
| 688 | |
| 689 | std::optional<ValueTypeCallbackTy> ValueTypeCallback; |
| 690 | |
| 691 | public: |
| 692 | BitcodeReader(BitstreamCursor Stream, StringRef Strtab, |
| 693 | StringRef ProducerIdentification, LLVMContext &Context); |
| 694 | |
| 695 | Error materializeForwardReferencedFunctions(); |
| 696 | |
| 697 | Error materialize(GlobalValue *GV) override; |
| 698 | Error materializeModule() override; |
| 699 | std::vector<StructType *> getIdentifiedStructTypes() const override; |
| 700 | |
| 701 | /// Main interface to parsing a bitcode buffer. |
| 702 | /// \returns true if an error occurred. |
| 703 | Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, |
| 704 | bool IsImporting, ParserCallbacks Callbacks = {}); |
| 705 | |
| 706 | static uint64_t decodeSignRotatedValue(uint64_t V); |
| 707 | |
| 708 | /// Materialize any deferred Metadata block. |
| 709 | Error materializeMetadata() override; |
| 710 | |
| 711 | void setStripDebugInfo() override; |
| 712 | |
| 713 | private: |
| 714 | std::vector<StructType *> IdentifiedStructTypes; |
| 715 | StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); |
| 716 | StructType *createIdentifiedStructType(LLVMContext &Context); |
| 717 | |
| 718 | static constexpr unsigned InvalidTypeID = ~0u; |
| 719 | |
| 720 | Type *getTypeByID(unsigned ID); |
| 721 | Type *getPtrElementTypeByID(unsigned ID); |
| 722 | unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0); |
| 723 | unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {}); |
| 724 | |
| 725 | void callValueTypeCallback(Value *F, unsigned TypeID); |
| 726 | Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB); |
| 727 | Expected<Constant *> getValueForInitializer(unsigned ID); |
| 728 | |
| 729 | Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID, |
| 730 | BasicBlock *ConstExprInsertBB) { |
| 731 | if (Ty && Ty->isMetadataTy()) |
| 732 | return MetadataAsValue::get(Context&: Ty->getContext(), MD: getFnMetadataByID(ID)); |
| 733 | return ValueList.getValueFwdRef(Idx: ID, Ty, TyID, ConstExprInsertBB); |
| 734 | } |
| 735 | |
| 736 | Metadata *getFnMetadataByID(unsigned ID) { |
| 737 | return MDLoader->getMetadataFwdRefOrLoad(Idx: ID); |
| 738 | } |
| 739 | |
| 740 | BasicBlock *getBasicBlock(unsigned ID) const { |
| 741 | if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID |
| 742 | return FunctionBBs[ID]; |
| 743 | } |
| 744 | |
| 745 | AttributeList getAttributes(unsigned i) const { |
| 746 | if (i-1 < MAttributes.size()) |
| 747 | return MAttributes[i-1]; |
| 748 | return AttributeList(); |
| 749 | } |
| 750 | |
| 751 | /// Read a value/type pair out of the specified record from slot 'Slot'. |
| 752 | /// Increment Slot past the number of slots used in the record. Return true on |
| 753 | /// failure. |
| 754 | bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, |
| 755 | unsigned InstNum, Value *&ResVal, unsigned &TypeID, |
| 756 | BasicBlock *ConstExprInsertBB) { |
| 757 | if (Slot == Record.size()) return true; |
| 758 | unsigned ValNo = (unsigned)Record[Slot++]; |
| 759 | // Adjust the ValNo, if it was encoded relative to the InstNum. |
| 760 | if (UseRelativeIDs) |
| 761 | ValNo = InstNum - ValNo; |
| 762 | if (ValNo < InstNum) { |
| 763 | // If this is not a forward reference, just return the value we already |
| 764 | // have. |
| 765 | TypeID = ValueList.getTypeID(ValNo); |
| 766 | ResVal = getFnValueByID(ID: ValNo, Ty: nullptr, TyID: TypeID, ConstExprInsertBB); |
| 767 | assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) && |
| 768 | "Incorrect type ID stored for value" ); |
| 769 | return ResVal == nullptr; |
| 770 | } |
| 771 | if (Slot == Record.size()) |
| 772 | return true; |
| 773 | |
| 774 | TypeID = (unsigned)Record[Slot++]; |
| 775 | ResVal = getFnValueByID(ID: ValNo, Ty: getTypeByID(ID: TypeID), TyID: TypeID, |
| 776 | ConstExprInsertBB); |
| 777 | return ResVal == nullptr; |
| 778 | } |
| 779 | |
| 780 | bool getValueOrMetadata(const SmallVectorImpl<uint64_t> &Record, |
| 781 | unsigned &Slot, unsigned InstNum, Value *&ResVal, |
| 782 | BasicBlock *ConstExprInsertBB) { |
| 783 | if (Slot == Record.size()) |
| 784 | return true; |
| 785 | unsigned ValID = Record[Slot++]; |
| 786 | if (ValID != static_cast<unsigned>(bitc::OB_METADATA)) { |
| 787 | unsigned TypeId; |
| 788 | return getValueTypePair(Record, Slot&: --Slot, InstNum, ResVal, TypeID&: TypeId, |
| 789 | ConstExprInsertBB); |
| 790 | } |
| 791 | if (Slot == Record.size()) |
| 792 | return true; |
| 793 | unsigned ValNo = InstNum - (unsigned)Record[Slot++]; |
| 794 | ResVal = MetadataAsValue::get(Context, MD: getFnMetadataByID(ID: ValNo)); |
| 795 | return false; |
| 796 | } |
| 797 | |
| 798 | /// Read a value out of the specified record from slot 'Slot'. Increment Slot |
| 799 | /// past the number of slots used by the value in the record. Return true if |
| 800 | /// there is an error. |
| 801 | bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, |
| 802 | unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, |
| 803 | BasicBlock *ConstExprInsertBB) { |
| 804 | if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB)) |
| 805 | return true; |
| 806 | // All values currently take a single record slot. |
| 807 | ++Slot; |
| 808 | return false; |
| 809 | } |
| 810 | |
| 811 | /// Like popValue, but does not increment the Slot number. |
| 812 | bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, |
| 813 | unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, |
| 814 | BasicBlock *ConstExprInsertBB) { |
| 815 | ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB); |
| 816 | return ResVal == nullptr; |
| 817 | } |
| 818 | |
| 819 | /// Version of getValue that returns ResVal directly, or 0 if there is an |
| 820 | /// error. |
| 821 | Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, |
| 822 | unsigned InstNum, Type *Ty, unsigned TyID, |
| 823 | BasicBlock *ConstExprInsertBB) { |
| 824 | if (Slot == Record.size()) return nullptr; |
| 825 | unsigned ValNo = (unsigned)Record[Slot]; |
| 826 | // Adjust the ValNo, if it was encoded relative to the InstNum. |
| 827 | if (UseRelativeIDs) |
| 828 | ValNo = InstNum - ValNo; |
| 829 | return getFnValueByID(ID: ValNo, Ty, TyID, ConstExprInsertBB); |
| 830 | } |
| 831 | |
| 832 | /// Like getValue, but decodes signed VBRs. |
| 833 | Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, |
| 834 | unsigned InstNum, Type *Ty, unsigned TyID, |
| 835 | BasicBlock *ConstExprInsertBB) { |
| 836 | if (Slot == Record.size()) return nullptr; |
| 837 | unsigned ValNo = (unsigned)decodeSignRotatedValue(V: Record[Slot]); |
| 838 | // Adjust the ValNo, if it was encoded relative to the InstNum. |
| 839 | if (UseRelativeIDs) |
| 840 | ValNo = InstNum - ValNo; |
| 841 | return getFnValueByID(ID: ValNo, Ty, TyID, ConstExprInsertBB); |
| 842 | } |
| 843 | |
| 844 | Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record, |
| 845 | unsigned &OpNum, |
| 846 | unsigned BitWidth) { |
| 847 | if (Record.size() - OpNum < 2) |
| 848 | return error(Message: "Too few records for range" ); |
| 849 | if (BitWidth > 64) { |
| 850 | unsigned LowerActiveWords = Record[OpNum]; |
| 851 | unsigned UpperActiveWords = Record[OpNum++] >> 32; |
| 852 | if (Record.size() - OpNum < LowerActiveWords + UpperActiveWords) |
| 853 | return error(Message: "Too few records for range" ); |
| 854 | APInt Lower = |
| 855 | readWideAPInt(Vals: ArrayRef(&Record[OpNum], LowerActiveWords), TypeBits: BitWidth); |
| 856 | OpNum += LowerActiveWords; |
| 857 | APInt Upper = |
| 858 | readWideAPInt(Vals: ArrayRef(&Record[OpNum], UpperActiveWords), TypeBits: BitWidth); |
| 859 | OpNum += UpperActiveWords; |
| 860 | return ConstantRange(Lower, Upper); |
| 861 | } else { |
| 862 | int64_t Start = BitcodeReader::decodeSignRotatedValue(V: Record[OpNum++]); |
| 863 | int64_t End = BitcodeReader::decodeSignRotatedValue(V: Record[OpNum++]); |
| 864 | return ConstantRange(APInt(BitWidth, Start, true), |
| 865 | APInt(BitWidth, End, true)); |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | Expected<ConstantRange> |
| 870 | readBitWidthAndConstantRange(ArrayRef<uint64_t> Record, unsigned &OpNum) { |
| 871 | if (Record.size() - OpNum < 1) |
| 872 | return error(Message: "Too few records for range" ); |
| 873 | unsigned BitWidth = Record[OpNum++]; |
| 874 | return readConstantRange(Record, OpNum, BitWidth); |
| 875 | } |
| 876 | |
| 877 | /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the |
| 878 | /// corresponding argument's pointee type. Also upgrades intrinsics that now |
| 879 | /// require an elementtype attribute. |
| 880 | Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys); |
| 881 | |
| 882 | /// Converts alignment exponent (i.e. power of two (or zero)) to the |
| 883 | /// corresponding alignment to use. If alignment is too large, returns |
| 884 | /// a corresponding error code. |
| 885 | Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment); |
| 886 | Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); |
| 887 | Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false, |
| 888 | ParserCallbacks Callbacks = {}); |
| 889 | |
| 890 | Error parseComdatRecord(ArrayRef<uint64_t> Record); |
| 891 | Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); |
| 892 | Error parseFunctionRecord(ArrayRef<uint64_t> Record); |
| 893 | Error parseGlobalIndirectSymbolRecord(unsigned BitCode, |
| 894 | ArrayRef<uint64_t> Record); |
| 895 | |
| 896 | Error parseAttributeBlock(); |
| 897 | Error parseAttributeGroupBlock(); |
| 898 | Error parseTypeTable(); |
| 899 | Error parseTypeTableBody(); |
| 900 | Error parseOperandBundleTags(); |
| 901 | Error parseSyncScopeNames(); |
| 902 | |
| 903 | Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, |
| 904 | unsigned NameIndex, Triple &TT); |
| 905 | void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, |
| 906 | ArrayRef<uint64_t> Record); |
| 907 | Error parseValueSymbolTable(uint64_t Offset = 0); |
| 908 | Error parseGlobalValueSymbolTable(); |
| 909 | Error parseConstants(); |
| 910 | Error rememberAndSkipFunctionBodies(); |
| 911 | Error rememberAndSkipFunctionBody(); |
| 912 | /// Save the positions of the Metadata blocks and skip parsing the blocks. |
| 913 | Error rememberAndSkipMetadata(); |
| 914 | Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); |
| 915 | Error parseFunctionBody(Function *F); |
| 916 | Error globalCleanup(); |
| 917 | Error resolveGlobalAndIndirectSymbolInits(); |
| 918 | Error parseUseLists(); |
| 919 | Error findFunctionInStream( |
| 920 | Function *F, |
| 921 | DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); |
| 922 | |
| 923 | SyncScope::ID getDecodedSyncScopeID(unsigned Val); |
| 924 | }; |
| 925 | |
| 926 | /// Class to manage reading and parsing function summary index bitcode |
| 927 | /// files/sections. |
| 928 | class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { |
| 929 | /// The module index built during parsing. |
| 930 | ModuleSummaryIndex &TheIndex; |
| 931 | |
| 932 | /// Indicates whether we have encountered a global value summary section |
| 933 | /// yet during parsing. |
| 934 | bool SeenGlobalValSummary = false; |
| 935 | |
| 936 | /// Indicates whether we have already parsed the VST, used for error checking. |
| 937 | bool SeenValueSymbolTable = false; |
| 938 | |
| 939 | /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. |
| 940 | /// Used to enable on-demand parsing of the VST. |
| 941 | uint64_t VSTOffset = 0; |
| 942 | |
| 943 | // Map to save ValueId to ValueInfo association that was recorded in the |
| 944 | // ValueSymbolTable. It is used after the VST is parsed to convert |
| 945 | // call graph edges read from the function summary from referencing |
| 946 | // callees by their ValueId to using the ValueInfo instead, which is how |
| 947 | // they are recorded in the summary index being built. |
| 948 | // We save a GUID which refers to the same global as the ValueInfo, but |
| 949 | // ignoring the linkage, i.e. for values other than local linkage they are |
| 950 | // identical (this is the second member). ValueInfo has the real GUID. |
| 951 | DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>> |
| 952 | ValueIdToValueInfoMap; |
| 953 | |
| 954 | /// Map populated during module path string table parsing, from the |
| 955 | /// module ID to a string reference owned by the index's module |
| 956 | /// path string table, used to correlate with combined index |
| 957 | /// summary records. |
| 958 | DenseMap<uint64_t, StringRef> ModuleIdMap; |
| 959 | |
| 960 | /// Original source file name recorded in a bitcode record. |
| 961 | std::string SourceFileName; |
| 962 | |
| 963 | /// The string identifier given to this module by the client, normally the |
| 964 | /// path to the bitcode file. |
| 965 | StringRef ModulePath; |
| 966 | |
| 967 | /// Callback to ask whether a symbol is the prevailing copy when invoked |
| 968 | /// during combined index building. |
| 969 | std::function<bool(GlobalValue::GUID)> IsPrevailing; |
| 970 | |
| 971 | /// Saves the stack ids from the STACK_IDS record to consult when adding stack |
| 972 | /// ids from the lists in the callsite and alloc entries to the index. |
| 973 | std::vector<uint64_t> StackIds; |
| 974 | |
| 975 | /// Linearized radix tree of allocation contexts. See the description above |
| 976 | /// the CallStackRadixTreeBuilder class in ProfileData/MemProf.h for format. |
| 977 | std::vector<uint64_t> RadixArray; |
| 978 | |
| 979 | public: |
| 980 | ModuleSummaryIndexBitcodeReader( |
| 981 | BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex, |
| 982 | StringRef ModulePath, |
| 983 | std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr); |
| 984 | |
| 985 | Error parseModule(); |
| 986 | |
| 987 | private: |
| 988 | void setValueGUID(uint64_t ValueID, StringRef ValueName, |
| 989 | GlobalValue::LinkageTypes Linkage, |
| 990 | StringRef SourceFileName); |
| 991 | Error parseValueSymbolTable( |
| 992 | uint64_t Offset, |
| 993 | DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); |
| 994 | SmallVector<ValueInfo, 0> makeRefList(ArrayRef<uint64_t> Record); |
| 995 | SmallVector<FunctionSummary::EdgeTy, 0> |
| 996 | makeCallList(ArrayRef<uint64_t> Record, bool IsOldProfileFormat, |
| 997 | bool HasProfile, bool HasRelBF); |
| 998 | Error parseEntireSummary(unsigned ID); |
| 999 | Error parseModuleStringTable(); |
| 1000 | void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record); |
| 1001 | void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot, |
| 1002 | TypeIdCompatibleVtableInfo &TypeId); |
| 1003 | std::vector<FunctionSummary::ParamAccess> |
| 1004 | parseParamAccesses(ArrayRef<uint64_t> Record); |
| 1005 | SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record, |
| 1006 | unsigned &I); |
| 1007 | |
| 1008 | template <bool AllowNullValueInfo = false> |
| 1009 | std::pair<ValueInfo, GlobalValue::GUID> |
| 1010 | getValueInfoFromValueId(unsigned ValueId); |
| 1011 | |
| 1012 | void addThisModule(); |
| 1013 | ModuleSummaryIndex::ModuleInfo *getThisModule(); |
| 1014 | }; |
| 1015 | |
| 1016 | } // end anonymous namespace |
| 1017 | |
| 1018 | std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, |
| 1019 | Error Err) { |
| 1020 | if (Err) { |
| 1021 | std::error_code EC; |
| 1022 | handleAllErrors(E: std::move(Err), Handlers: [&](ErrorInfoBase &EIB) { |
| 1023 | EC = EIB.convertToErrorCode(); |
| 1024 | Ctx.emitError(ErrorStr: EIB.message()); |
| 1025 | }); |
| 1026 | return EC; |
| 1027 | } |
| 1028 | return std::error_code(); |
| 1029 | } |
| 1030 | |
| 1031 | BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, |
| 1032 | StringRef ProducerIdentification, |
| 1033 | LLVMContext &Context) |
| 1034 | : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), |
| 1035 | ValueList(this->Stream.SizeInBytes(), |
| 1036 | [this](unsigned ValID, BasicBlock *InsertBB) { |
| 1037 | return materializeValue(ValID, InsertBB); |
| 1038 | }) { |
| 1039 | this->ProducerIdentification = std::string(ProducerIdentification); |
| 1040 | } |
| 1041 | |
| 1042 | Error BitcodeReader::materializeForwardReferencedFunctions() { |
| 1043 | if (WillMaterializeAllForwardRefs) |
| 1044 | return Error::success(); |
| 1045 | |
| 1046 | // Prevent recursion. |
| 1047 | WillMaterializeAllForwardRefs = true; |
| 1048 | |
| 1049 | while (!BasicBlockFwdRefQueue.empty()) { |
| 1050 | Function *F = BasicBlockFwdRefQueue.front(); |
| 1051 | BasicBlockFwdRefQueue.pop_front(); |
| 1052 | assert(F && "Expected valid function" ); |
| 1053 | if (!BasicBlockFwdRefs.count(Val: F)) |
| 1054 | // Already materialized. |
| 1055 | continue; |
| 1056 | |
| 1057 | // Check for a function that isn't materializable to prevent an infinite |
| 1058 | // loop. When parsing a blockaddress stored in a global variable, there |
| 1059 | // isn't a trivial way to check if a function will have a body without a |
| 1060 | // linear search through FunctionsWithBodies, so just check it here. |
| 1061 | if (!F->isMaterializable()) |
| 1062 | return error(Message: "Never resolved function from blockaddress" ); |
| 1063 | |
| 1064 | // Try to materialize F. |
| 1065 | if (Error Err = materialize(GV: F)) |
| 1066 | return Err; |
| 1067 | } |
| 1068 | assert(BasicBlockFwdRefs.empty() && "Function missing from queue" ); |
| 1069 | |
| 1070 | for (Function *F : BackwardRefFunctions) |
| 1071 | if (Error Err = materialize(GV: F)) |
| 1072 | return Err; |
| 1073 | BackwardRefFunctions.clear(); |
| 1074 | |
| 1075 | // Reset state. |
| 1076 | WillMaterializeAllForwardRefs = false; |
| 1077 | return Error::success(); |
| 1078 | } |
| 1079 | |
| 1080 | //===----------------------------------------------------------------------===// |
| 1081 | // Helper functions to implement forward reference resolution, etc. |
| 1082 | //===----------------------------------------------------------------------===// |
| 1083 | |
| 1084 | static bool hasImplicitComdat(size_t Val) { |
| 1085 | switch (Val) { |
| 1086 | default: |
| 1087 | return false; |
| 1088 | case 1: // Old WeakAnyLinkage |
| 1089 | case 4: // Old LinkOnceAnyLinkage |
| 1090 | case 10: // Old WeakODRLinkage |
| 1091 | case 11: // Old LinkOnceODRLinkage |
| 1092 | return true; |
| 1093 | } |
| 1094 | } |
| 1095 | |
| 1096 | static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { |
| 1097 | switch (Val) { |
| 1098 | default: // Map unknown/new linkages to external |
| 1099 | case 0: |
| 1100 | return GlobalValue::ExternalLinkage; |
| 1101 | case 2: |
| 1102 | return GlobalValue::AppendingLinkage; |
| 1103 | case 3: |
| 1104 | return GlobalValue::InternalLinkage; |
| 1105 | case 5: |
| 1106 | return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage |
| 1107 | case 6: |
| 1108 | return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage |
| 1109 | case 7: |
| 1110 | return GlobalValue::ExternalWeakLinkage; |
| 1111 | case 8: |
| 1112 | return GlobalValue::CommonLinkage; |
| 1113 | case 9: |
| 1114 | return GlobalValue::PrivateLinkage; |
| 1115 | case 12: |
| 1116 | return GlobalValue::AvailableExternallyLinkage; |
| 1117 | case 13: |
| 1118 | return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage |
| 1119 | case 14: |
| 1120 | return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage |
| 1121 | case 15: |
| 1122 | return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage |
| 1123 | case 1: // Old value with implicit comdat. |
| 1124 | case 16: |
| 1125 | return GlobalValue::WeakAnyLinkage; |
| 1126 | case 10: // Old value with implicit comdat. |
| 1127 | case 17: |
| 1128 | return GlobalValue::WeakODRLinkage; |
| 1129 | case 4: // Old value with implicit comdat. |
| 1130 | case 18: |
| 1131 | return GlobalValue::LinkOnceAnyLinkage; |
| 1132 | case 11: // Old value with implicit comdat. |
| 1133 | case 19: |
| 1134 | return GlobalValue::LinkOnceODRLinkage; |
| 1135 | } |
| 1136 | } |
| 1137 | |
| 1138 | static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { |
| 1139 | FunctionSummary::FFlags Flags; |
| 1140 | Flags.ReadNone = RawFlags & 0x1; |
| 1141 | Flags.ReadOnly = (RawFlags >> 1) & 0x1; |
| 1142 | Flags.NoRecurse = (RawFlags >> 2) & 0x1; |
| 1143 | Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; |
| 1144 | Flags.NoInline = (RawFlags >> 4) & 0x1; |
| 1145 | Flags.AlwaysInline = (RawFlags >> 5) & 0x1; |
| 1146 | Flags.NoUnwind = (RawFlags >> 6) & 0x1; |
| 1147 | Flags.MayThrow = (RawFlags >> 7) & 0x1; |
| 1148 | Flags.HasUnknownCall = (RawFlags >> 8) & 0x1; |
| 1149 | Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1; |
| 1150 | return Flags; |
| 1151 | } |
| 1152 | |
| 1153 | // Decode the flags for GlobalValue in the summary. The bits for each attribute: |
| 1154 | // |
| 1155 | // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7, |
| 1156 | // visibility: [8, 10). |
| 1157 | static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, |
| 1158 | uint64_t Version) { |
| 1159 | // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage |
| 1160 | // like getDecodedLinkage() above. Any future change to the linkage enum and |
| 1161 | // to getDecodedLinkage() will need to be taken into account here as above. |
| 1162 | auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits |
| 1163 | auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits |
| 1164 | auto IK = GlobalValueSummary::ImportKind((RawFlags >> 10) & 1); // 1 bit |
| 1165 | RawFlags = RawFlags >> 4; |
| 1166 | bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; |
| 1167 | // The Live flag wasn't introduced until version 3. For dead stripping |
| 1168 | // to work correctly on earlier versions, we must conservatively treat all |
| 1169 | // values as live. |
| 1170 | bool Live = (RawFlags & 0x2) || Version < 3; |
| 1171 | bool Local = (RawFlags & 0x4); |
| 1172 | bool AutoHide = (RawFlags & 0x8); |
| 1173 | |
| 1174 | return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport, |
| 1175 | Live, Local, AutoHide, IK); |
| 1176 | } |
| 1177 | |
| 1178 | // Decode the flags for GlobalVariable in the summary |
| 1179 | static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) { |
| 1180 | return GlobalVarSummary::GVarFlags( |
| 1181 | (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false, |
| 1182 | (RawFlags & 0x4) ? true : false, |
| 1183 | (GlobalObject::VCallVisibility)(RawFlags >> 3)); |
| 1184 | } |
| 1185 | |
| 1186 | static std::pair<CalleeInfo::HotnessType, bool> |
| 1187 | getDecodedHotnessCallEdgeInfo(uint64_t RawFlags) { |
| 1188 | CalleeInfo::HotnessType Hotness = |
| 1189 | static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits |
| 1190 | bool HasTailCall = (RawFlags & 0x8); // 1 bit |
| 1191 | return {Hotness, HasTailCall}; |
| 1192 | } |
| 1193 | |
| 1194 | static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, |
| 1195 | bool &HasTailCall) { |
| 1196 | static constexpr uint64_t RelBlockFreqMask = |
| 1197 | (1 << CalleeInfo::RelBlockFreqBits) - 1; |
| 1198 | RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits |
| 1199 | HasTailCall = (RawFlags & (1 << CalleeInfo::RelBlockFreqBits)); // 1 bit |
| 1200 | } |
| 1201 | |
| 1202 | static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { |
| 1203 | switch (Val) { |
| 1204 | default: // Map unknown visibilities to default. |
| 1205 | case 0: return GlobalValue::DefaultVisibility; |
| 1206 | case 1: return GlobalValue::HiddenVisibility; |
| 1207 | case 2: return GlobalValue::ProtectedVisibility; |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | static GlobalValue::DLLStorageClassTypes |
| 1212 | getDecodedDLLStorageClass(unsigned Val) { |
| 1213 | switch (Val) { |
| 1214 | default: // Map unknown values to default. |
| 1215 | case 0: return GlobalValue::DefaultStorageClass; |
| 1216 | case 1: return GlobalValue::DLLImportStorageClass; |
| 1217 | case 2: return GlobalValue::DLLExportStorageClass; |
| 1218 | } |
| 1219 | } |
| 1220 | |
| 1221 | static bool getDecodedDSOLocal(unsigned Val) { |
| 1222 | switch(Val) { |
| 1223 | default: // Map unknown values to preemptable. |
| 1224 | case 0: return false; |
| 1225 | case 1: return true; |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) { |
| 1230 | switch (Val) { |
| 1231 | case 1: |
| 1232 | return CodeModel::Tiny; |
| 1233 | case 2: |
| 1234 | return CodeModel::Small; |
| 1235 | case 3: |
| 1236 | return CodeModel::Kernel; |
| 1237 | case 4: |
| 1238 | return CodeModel::Medium; |
| 1239 | case 5: |
| 1240 | return CodeModel::Large; |
| 1241 | } |
| 1242 | |
| 1243 | return {}; |
| 1244 | } |
| 1245 | |
| 1246 | static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { |
| 1247 | switch (Val) { |
| 1248 | case 0: return GlobalVariable::NotThreadLocal; |
| 1249 | default: // Map unknown non-zero value to general dynamic. |
| 1250 | case 1: return GlobalVariable::GeneralDynamicTLSModel; |
| 1251 | case 2: return GlobalVariable::LocalDynamicTLSModel; |
| 1252 | case 3: return GlobalVariable::InitialExecTLSModel; |
| 1253 | case 4: return GlobalVariable::LocalExecTLSModel; |
| 1254 | } |
| 1255 | } |
| 1256 | |
| 1257 | static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { |
| 1258 | switch (Val) { |
| 1259 | default: // Map unknown to UnnamedAddr::None. |
| 1260 | case 0: return GlobalVariable::UnnamedAddr::None; |
| 1261 | case 1: return GlobalVariable::UnnamedAddr::Global; |
| 1262 | case 2: return GlobalVariable::UnnamedAddr::Local; |
| 1263 | } |
| 1264 | } |
| 1265 | |
| 1266 | static int getDecodedCastOpcode(unsigned Val) { |
| 1267 | switch (Val) { |
| 1268 | default: return -1; |
| 1269 | case bitc::CAST_TRUNC : return Instruction::Trunc; |
| 1270 | case bitc::CAST_ZEXT : return Instruction::ZExt; |
| 1271 | case bitc::CAST_SEXT : return Instruction::SExt; |
| 1272 | case bitc::CAST_FPTOUI : return Instruction::FPToUI; |
| 1273 | case bitc::CAST_FPTOSI : return Instruction::FPToSI; |
| 1274 | case bitc::CAST_UITOFP : return Instruction::UIToFP; |
| 1275 | case bitc::CAST_SITOFP : return Instruction::SIToFP; |
| 1276 | case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; |
| 1277 | case bitc::CAST_FPEXT : return Instruction::FPExt; |
| 1278 | case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; |
| 1279 | case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; |
| 1280 | case bitc::CAST_BITCAST : return Instruction::BitCast; |
| 1281 | case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; |
| 1282 | } |
| 1283 | } |
| 1284 | |
| 1285 | static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) { |
| 1286 | bool IsFP = Ty->isFPOrFPVectorTy(); |
| 1287 | // UnOps are only valid for int/fp or vector of int/fp types |
| 1288 | if (!IsFP && !Ty->isIntOrIntVectorTy()) |
| 1289 | return -1; |
| 1290 | |
| 1291 | switch (Val) { |
| 1292 | default: |
| 1293 | return -1; |
| 1294 | case bitc::UNOP_FNEG: |
| 1295 | return IsFP ? Instruction::FNeg : -1; |
| 1296 | } |
| 1297 | } |
| 1298 | |
| 1299 | static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { |
| 1300 | bool IsFP = Ty->isFPOrFPVectorTy(); |
| 1301 | // BinOps are only valid for int/fp or vector of int/fp types |
| 1302 | if (!IsFP && !Ty->isIntOrIntVectorTy()) |
| 1303 | return -1; |
| 1304 | |
| 1305 | switch (Val) { |
| 1306 | default: |
| 1307 | return -1; |
| 1308 | case bitc::BINOP_ADD: |
| 1309 | return IsFP ? Instruction::FAdd : Instruction::Add; |
| 1310 | case bitc::BINOP_SUB: |
| 1311 | return IsFP ? Instruction::FSub : Instruction::Sub; |
| 1312 | case bitc::BINOP_MUL: |
| 1313 | return IsFP ? Instruction::FMul : Instruction::Mul; |
| 1314 | case bitc::BINOP_UDIV: |
| 1315 | return IsFP ? -1 : Instruction::UDiv; |
| 1316 | case bitc::BINOP_SDIV: |
| 1317 | return IsFP ? Instruction::FDiv : Instruction::SDiv; |
| 1318 | case bitc::BINOP_UREM: |
| 1319 | return IsFP ? -1 : Instruction::URem; |
| 1320 | case bitc::BINOP_SREM: |
| 1321 | return IsFP ? Instruction::FRem : Instruction::SRem; |
| 1322 | case bitc::BINOP_SHL: |
| 1323 | return IsFP ? -1 : Instruction::Shl; |
| 1324 | case bitc::BINOP_LSHR: |
| 1325 | return IsFP ? -1 : Instruction::LShr; |
| 1326 | case bitc::BINOP_ASHR: |
| 1327 | return IsFP ? -1 : Instruction::AShr; |
| 1328 | case bitc::BINOP_AND: |
| 1329 | return IsFP ? -1 : Instruction::And; |
| 1330 | case bitc::BINOP_OR: |
| 1331 | return IsFP ? -1 : Instruction::Or; |
| 1332 | case bitc::BINOP_XOR: |
| 1333 | return IsFP ? -1 : Instruction::Xor; |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { |
| 1338 | switch (Val) { |
| 1339 | default: return AtomicRMWInst::BAD_BINOP; |
| 1340 | case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; |
| 1341 | case bitc::RMW_ADD: return AtomicRMWInst::Add; |
| 1342 | case bitc::RMW_SUB: return AtomicRMWInst::Sub; |
| 1343 | case bitc::RMW_AND: return AtomicRMWInst::And; |
| 1344 | case bitc::RMW_NAND: return AtomicRMWInst::Nand; |
| 1345 | case bitc::RMW_OR: return AtomicRMWInst::Or; |
| 1346 | case bitc::RMW_XOR: return AtomicRMWInst::Xor; |
| 1347 | case bitc::RMW_MAX: return AtomicRMWInst::Max; |
| 1348 | case bitc::RMW_MIN: return AtomicRMWInst::Min; |
| 1349 | case bitc::RMW_UMAX: return AtomicRMWInst::UMax; |
| 1350 | case bitc::RMW_UMIN: return AtomicRMWInst::UMin; |
| 1351 | case bitc::RMW_FADD: return AtomicRMWInst::FAdd; |
| 1352 | case bitc::RMW_FSUB: return AtomicRMWInst::FSub; |
| 1353 | case bitc::RMW_FMAX: return AtomicRMWInst::FMax; |
| 1354 | case bitc::RMW_FMIN: return AtomicRMWInst::FMin; |
| 1355 | case bitc::RMW_FMAXIMUM: |
| 1356 | return AtomicRMWInst::FMaximum; |
| 1357 | case bitc::RMW_FMINIMUM: |
| 1358 | return AtomicRMWInst::FMinimum; |
| 1359 | case bitc::RMW_UINC_WRAP: |
| 1360 | return AtomicRMWInst::UIncWrap; |
| 1361 | case bitc::RMW_UDEC_WRAP: |
| 1362 | return AtomicRMWInst::UDecWrap; |
| 1363 | case bitc::RMW_USUB_COND: |
| 1364 | return AtomicRMWInst::USubCond; |
| 1365 | case bitc::RMW_USUB_SAT: |
| 1366 | return AtomicRMWInst::USubSat; |
| 1367 | } |
| 1368 | } |
| 1369 | |
| 1370 | static AtomicOrdering getDecodedOrdering(unsigned Val) { |
| 1371 | switch (Val) { |
| 1372 | case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; |
| 1373 | case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; |
| 1374 | case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; |
| 1375 | case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; |
| 1376 | case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; |
| 1377 | case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; |
| 1378 | default: // Map unknown orderings to sequentially-consistent. |
| 1379 | case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; |
| 1380 | } |
| 1381 | } |
| 1382 | |
| 1383 | static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { |
| 1384 | switch (Val) { |
| 1385 | default: // Map unknown selection kinds to any. |
| 1386 | case bitc::COMDAT_SELECTION_KIND_ANY: |
| 1387 | return Comdat::Any; |
| 1388 | case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: |
| 1389 | return Comdat::ExactMatch; |
| 1390 | case bitc::COMDAT_SELECTION_KIND_LARGEST: |
| 1391 | return Comdat::Largest; |
| 1392 | case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: |
| 1393 | return Comdat::NoDeduplicate; |
| 1394 | case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: |
| 1395 | return Comdat::SameSize; |
| 1396 | } |
| 1397 | } |
| 1398 | |
| 1399 | static FastMathFlags getDecodedFastMathFlags(unsigned Val) { |
| 1400 | FastMathFlags FMF; |
| 1401 | if (0 != (Val & bitc::UnsafeAlgebra)) |
| 1402 | FMF.setFast(); |
| 1403 | if (0 != (Val & bitc::AllowReassoc)) |
| 1404 | FMF.setAllowReassoc(); |
| 1405 | if (0 != (Val & bitc::NoNaNs)) |
| 1406 | FMF.setNoNaNs(); |
| 1407 | if (0 != (Val & bitc::NoInfs)) |
| 1408 | FMF.setNoInfs(); |
| 1409 | if (0 != (Val & bitc::NoSignedZeros)) |
| 1410 | FMF.setNoSignedZeros(); |
| 1411 | if (0 != (Val & bitc::AllowReciprocal)) |
| 1412 | FMF.setAllowReciprocal(); |
| 1413 | if (0 != (Val & bitc::AllowContract)) |
| 1414 | FMF.setAllowContract(true); |
| 1415 | if (0 != (Val & bitc::ApproxFunc)) |
| 1416 | FMF.setApproxFunc(); |
| 1417 | return FMF; |
| 1418 | } |
| 1419 | |
| 1420 | static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { |
| 1421 | // A GlobalValue with local linkage cannot have a DLL storage class. |
| 1422 | if (GV->hasLocalLinkage()) |
| 1423 | return; |
| 1424 | switch (Val) { |
| 1425 | case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; |
| 1426 | case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; |
| 1427 | } |
| 1428 | } |
| 1429 | |
| 1430 | Type *BitcodeReader::getTypeByID(unsigned ID) { |
| 1431 | // The type table size is always specified correctly. |
| 1432 | if (ID >= TypeList.size()) |
| 1433 | return nullptr; |
| 1434 | |
| 1435 | if (Type *Ty = TypeList[ID]) |
| 1436 | return Ty; |
| 1437 | |
| 1438 | // If we have a forward reference, the only possible case is when it is to a |
| 1439 | // named struct. Just create a placeholder for now. |
| 1440 | return TypeList[ID] = createIdentifiedStructType(Context); |
| 1441 | } |
| 1442 | |
| 1443 | unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) { |
| 1444 | auto It = ContainedTypeIDs.find(Val: ID); |
| 1445 | if (It == ContainedTypeIDs.end()) |
| 1446 | return InvalidTypeID; |
| 1447 | |
| 1448 | if (Idx >= It->second.size()) |
| 1449 | return InvalidTypeID; |
| 1450 | |
| 1451 | return It->second[Idx]; |
| 1452 | } |
| 1453 | |
| 1454 | Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) { |
| 1455 | if (ID >= TypeList.size()) |
| 1456 | return nullptr; |
| 1457 | |
| 1458 | Type *Ty = TypeList[ID]; |
| 1459 | if (!Ty->isPointerTy()) |
| 1460 | return nullptr; |
| 1461 | |
| 1462 | return getTypeByID(ID: getContainedTypeID(ID, Idx: 0)); |
| 1463 | } |
| 1464 | |
| 1465 | unsigned BitcodeReader::getVirtualTypeID(Type *Ty, |
| 1466 | ArrayRef<unsigned> ChildTypeIDs) { |
| 1467 | unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0]; |
| 1468 | auto CacheKey = std::make_pair(x&: Ty, y&: ChildTypeID); |
| 1469 | auto It = VirtualTypeIDs.find(Val: CacheKey); |
| 1470 | if (It != VirtualTypeIDs.end()) { |
| 1471 | // The cmpxchg return value is the only place we need more than one |
| 1472 | // contained type ID, however the second one will always be the same (i1), |
| 1473 | // so we don't need to include it in the cache key. This asserts that the |
| 1474 | // contained types are indeed as expected and there are no collisions. |
| 1475 | assert((ChildTypeIDs.empty() || |
| 1476 | ContainedTypeIDs[It->second] == ChildTypeIDs) && |
| 1477 | "Incorrect cached contained type IDs" ); |
| 1478 | return It->second; |
| 1479 | } |
| 1480 | |
| 1481 | unsigned TypeID = TypeList.size(); |
| 1482 | TypeList.push_back(x: Ty); |
| 1483 | if (!ChildTypeIDs.empty()) |
| 1484 | append_range(C&: ContainedTypeIDs[TypeID], R&: ChildTypeIDs); |
| 1485 | VirtualTypeIDs.insert(KV: {CacheKey, TypeID}); |
| 1486 | return TypeID; |
| 1487 | } |
| 1488 | |
| 1489 | static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags) { |
| 1490 | GEPNoWrapFlags NW; |
| 1491 | if (Flags & (1 << bitc::GEP_INBOUNDS)) |
| 1492 | NW |= GEPNoWrapFlags::inBounds(); |
| 1493 | if (Flags & (1 << bitc::GEP_NUSW)) |
| 1494 | NW |= GEPNoWrapFlags::noUnsignedSignedWrap(); |
| 1495 | if (Flags & (1 << bitc::GEP_NUW)) |
| 1496 | NW |= GEPNoWrapFlags::noUnsignedWrap(); |
| 1497 | return NW; |
| 1498 | } |
| 1499 | |
| 1500 | static bool isConstExprSupported(const BitcodeConstant *BC) { |
| 1501 | uint8_t Opcode = BC->Opcode; |
| 1502 | |
| 1503 | // These are not real constant expressions, always consider them supported. |
| 1504 | if (Opcode >= BitcodeConstant::FirstSpecialOpcode) |
| 1505 | return true; |
| 1506 | |
| 1507 | // If -expand-constant-exprs is set, we want to consider all expressions |
| 1508 | // as unsupported. |
| 1509 | if (ExpandConstantExprs) |
| 1510 | return false; |
| 1511 | |
| 1512 | if (Instruction::isBinaryOp(Opcode)) |
| 1513 | return ConstantExpr::isSupportedBinOp(Opcode); |
| 1514 | |
| 1515 | if (Instruction::isCast(Opcode)) |
| 1516 | return ConstantExpr::isSupportedCastOp(Opcode); |
| 1517 | |
| 1518 | if (Opcode == Instruction::GetElementPtr) |
| 1519 | return ConstantExpr::isSupportedGetElementPtr(SrcElemTy: BC->SrcElemTy); |
| 1520 | |
| 1521 | switch (Opcode) { |
| 1522 | case Instruction::FNeg: |
| 1523 | case Instruction::Select: |
| 1524 | case Instruction::ICmp: |
| 1525 | case Instruction::FCmp: |
| 1526 | return false; |
| 1527 | default: |
| 1528 | return true; |
| 1529 | } |
| 1530 | } |
| 1531 | |
| 1532 | Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID, |
| 1533 | BasicBlock *InsertBB) { |
| 1534 | // Quickly handle the case where there is no BitcodeConstant to resolve. |
| 1535 | if (StartValID < ValueList.size() && ValueList[StartValID] && |
| 1536 | !isa<BitcodeConstant>(Val: ValueList[StartValID])) |
| 1537 | return ValueList[StartValID]; |
| 1538 | |
| 1539 | SmallDenseMap<unsigned, Value *> MaterializedValues; |
| 1540 | SmallVector<unsigned> Worklist; |
| 1541 | Worklist.push_back(Elt: StartValID); |
| 1542 | while (!Worklist.empty()) { |
| 1543 | unsigned ValID = Worklist.back(); |
| 1544 | if (MaterializedValues.count(Val: ValID)) { |
| 1545 | // Duplicate expression that was already handled. |
| 1546 | Worklist.pop_back(); |
| 1547 | continue; |
| 1548 | } |
| 1549 | |
| 1550 | if (ValID >= ValueList.size() || !ValueList[ValID]) |
| 1551 | return error(Message: "Invalid value ID" ); |
| 1552 | |
| 1553 | Value *V = ValueList[ValID]; |
| 1554 | auto *BC = dyn_cast<BitcodeConstant>(Val: V); |
| 1555 | if (!BC) { |
| 1556 | MaterializedValues.insert(KV: {ValID, V}); |
| 1557 | Worklist.pop_back(); |
| 1558 | continue; |
| 1559 | } |
| 1560 | |
| 1561 | // Iterate in reverse, so values will get popped from the worklist in |
| 1562 | // expected order. |
| 1563 | SmallVector<Value *> Ops; |
| 1564 | for (unsigned OpID : reverse(C: BC->getOperandIDs())) { |
| 1565 | auto It = MaterializedValues.find(Val: OpID); |
| 1566 | if (It != MaterializedValues.end()) |
| 1567 | Ops.push_back(Elt: It->second); |
| 1568 | else |
| 1569 | Worklist.push_back(Elt: OpID); |
| 1570 | } |
| 1571 | |
| 1572 | // Some expressions have not been resolved yet, handle them first and then |
| 1573 | // revisit this one. |
| 1574 | if (Ops.size() != BC->getOperandIDs().size()) |
| 1575 | continue; |
| 1576 | std::reverse(first: Ops.begin(), last: Ops.end()); |
| 1577 | |
| 1578 | SmallVector<Constant *> ConstOps; |
| 1579 | for (Value *Op : Ops) |
| 1580 | if (auto *C = dyn_cast<Constant>(Val: Op)) |
| 1581 | ConstOps.push_back(Elt: C); |
| 1582 | |
| 1583 | // Materialize as constant expression if possible. |
| 1584 | if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) { |
| 1585 | Constant *C; |
| 1586 | if (Instruction::isCast(Opcode: BC->Opcode)) { |
| 1587 | C = UpgradeBitCastExpr(Opc: BC->Opcode, C: ConstOps[0], DestTy: BC->getType()); |
| 1588 | if (!C) |
| 1589 | C = ConstantExpr::getCast(ops: BC->Opcode, C: ConstOps[0], Ty: BC->getType()); |
| 1590 | } else if (Instruction::isBinaryOp(Opcode: BC->Opcode)) { |
| 1591 | C = ConstantExpr::get(Opcode: BC->Opcode, C1: ConstOps[0], C2: ConstOps[1], Flags: BC->Flags); |
| 1592 | } else { |
| 1593 | switch (BC->Opcode) { |
| 1594 | case BitcodeConstant::ConstantPtrAuthOpcode: { |
| 1595 | auto *Key = dyn_cast<ConstantInt>(Val: ConstOps[1]); |
| 1596 | if (!Key) |
| 1597 | return error(Message: "ptrauth key operand must be ConstantInt" ); |
| 1598 | |
| 1599 | auto *Disc = dyn_cast<ConstantInt>(Val: ConstOps[2]); |
| 1600 | if (!Disc) |
| 1601 | return error(Message: "ptrauth disc operand must be ConstantInt" ); |
| 1602 | |
| 1603 | C = ConstantPtrAuth::get(Ptr: ConstOps[0], Key, Disc, AddrDisc: ConstOps[3]); |
| 1604 | break; |
| 1605 | } |
| 1606 | case BitcodeConstant::NoCFIOpcode: { |
| 1607 | auto *GV = dyn_cast<GlobalValue>(Val: ConstOps[0]); |
| 1608 | if (!GV) |
| 1609 | return error(Message: "no_cfi operand must be GlobalValue" ); |
| 1610 | C = NoCFIValue::get(GV); |
| 1611 | break; |
| 1612 | } |
| 1613 | case BitcodeConstant::DSOLocalEquivalentOpcode: { |
| 1614 | auto *GV = dyn_cast<GlobalValue>(Val: ConstOps[0]); |
| 1615 | if (!GV) |
| 1616 | return error(Message: "dso_local operand must be GlobalValue" ); |
| 1617 | C = DSOLocalEquivalent::get(GV); |
| 1618 | break; |
| 1619 | } |
| 1620 | case BitcodeConstant::BlockAddressOpcode: { |
| 1621 | Function *Fn = dyn_cast<Function>(Val: ConstOps[0]); |
| 1622 | if (!Fn) |
| 1623 | return error(Message: "blockaddress operand must be a function" ); |
| 1624 | |
| 1625 | // If the function is already parsed we can insert the block address |
| 1626 | // right away. |
| 1627 | BasicBlock *BB; |
| 1628 | unsigned BBID = BC->BlockAddressBB; |
| 1629 | if (!BBID) |
| 1630 | // Invalid reference to entry block. |
| 1631 | return error(Message: "Invalid ID" ); |
| 1632 | if (!Fn->empty()) { |
| 1633 | Function::iterator BBI = Fn->begin(), BBE = Fn->end(); |
| 1634 | for (size_t I = 0, E = BBID; I != E; ++I) { |
| 1635 | if (BBI == BBE) |
| 1636 | return error(Message: "Invalid ID" ); |
| 1637 | ++BBI; |
| 1638 | } |
| 1639 | BB = &*BBI; |
| 1640 | } else { |
| 1641 | // Otherwise insert a placeholder and remember it so it can be |
| 1642 | // inserted when the function is parsed. |
| 1643 | auto &FwdBBs = BasicBlockFwdRefs[Fn]; |
| 1644 | if (FwdBBs.empty()) |
| 1645 | BasicBlockFwdRefQueue.push_back(x: Fn); |
| 1646 | if (FwdBBs.size() < BBID + 1) |
| 1647 | FwdBBs.resize(new_size: BBID + 1); |
| 1648 | if (!FwdBBs[BBID]) |
| 1649 | FwdBBs[BBID] = BasicBlock::Create(Context); |
| 1650 | BB = FwdBBs[BBID]; |
| 1651 | } |
| 1652 | C = BlockAddress::get(Ty: Fn->getType(), BB); |
| 1653 | break; |
| 1654 | } |
| 1655 | case BitcodeConstant::ConstantStructOpcode: { |
| 1656 | auto *ST = cast<StructType>(Val: BC->getType()); |
| 1657 | if (ST->getNumElements() != ConstOps.size()) |
| 1658 | return error(Message: "Invalid number of elements in struct initializer" ); |
| 1659 | |
| 1660 | for (const auto [Ty, Op] : zip(t: ST->elements(), u&: ConstOps)) |
| 1661 | if (Op->getType() != Ty) |
| 1662 | return error(Message: "Incorrect type in struct initializer" ); |
| 1663 | |
| 1664 | C = ConstantStruct::get(T: ST, V: ConstOps); |
| 1665 | break; |
| 1666 | } |
| 1667 | case BitcodeConstant::ConstantArrayOpcode: { |
| 1668 | auto *AT = cast<ArrayType>(Val: BC->getType()); |
| 1669 | if (AT->getNumElements() != ConstOps.size()) |
| 1670 | return error(Message: "Invalid number of elements in array initializer" ); |
| 1671 | |
| 1672 | for (Constant *Op : ConstOps) |
| 1673 | if (Op->getType() != AT->getElementType()) |
| 1674 | return error(Message: "Incorrect type in array initializer" ); |
| 1675 | |
| 1676 | C = ConstantArray::get(T: AT, V: ConstOps); |
| 1677 | break; |
| 1678 | } |
| 1679 | case BitcodeConstant::ConstantVectorOpcode: { |
| 1680 | auto *VT = cast<FixedVectorType>(Val: BC->getType()); |
| 1681 | if (VT->getNumElements() != ConstOps.size()) |
| 1682 | return error(Message: "Invalid number of elements in vector initializer" ); |
| 1683 | |
| 1684 | for (Constant *Op : ConstOps) |
| 1685 | if (Op->getType() != VT->getElementType()) |
| 1686 | return error(Message: "Incorrect type in vector initializer" ); |
| 1687 | |
| 1688 | C = ConstantVector::get(V: ConstOps); |
| 1689 | break; |
| 1690 | } |
| 1691 | case Instruction::GetElementPtr: |
| 1692 | C = ConstantExpr::getGetElementPtr( |
| 1693 | Ty: BC->SrcElemTy, C: ConstOps[0], IdxList: ArrayRef(ConstOps).drop_front(), |
| 1694 | NW: toGEPNoWrapFlags(Flags: BC->Flags), InRange: BC->getInRange()); |
| 1695 | break; |
| 1696 | case Instruction::ExtractElement: |
| 1697 | C = ConstantExpr::getExtractElement(Vec: ConstOps[0], Idx: ConstOps[1]); |
| 1698 | break; |
| 1699 | case Instruction::InsertElement: |
| 1700 | C = ConstantExpr::getInsertElement(Vec: ConstOps[0], Elt: ConstOps[1], |
| 1701 | Idx: ConstOps[2]); |
| 1702 | break; |
| 1703 | case Instruction::ShuffleVector: { |
| 1704 | SmallVector<int, 16> Mask; |
| 1705 | ShuffleVectorInst::getShuffleMask(Mask: ConstOps[2], Result&: Mask); |
| 1706 | C = ConstantExpr::getShuffleVector(V1: ConstOps[0], V2: ConstOps[1], Mask); |
| 1707 | break; |
| 1708 | } |
| 1709 | default: |
| 1710 | llvm_unreachable("Unhandled bitcode constant" ); |
| 1711 | } |
| 1712 | } |
| 1713 | |
| 1714 | // Cache resolved constant. |
| 1715 | ValueList.replaceValueWithoutRAUW(ValNo: ValID, NewV: C); |
| 1716 | MaterializedValues.insert(KV: {ValID, C}); |
| 1717 | Worklist.pop_back(); |
| 1718 | continue; |
| 1719 | } |
| 1720 | |
| 1721 | if (!InsertBB) |
| 1722 | return error(Message: Twine("Value referenced by initializer is an unsupported " |
| 1723 | "constant expression of type " ) + |
| 1724 | BC->getOpcodeName()); |
| 1725 | |
| 1726 | // Materialize as instructions if necessary. |
| 1727 | Instruction *I; |
| 1728 | if (Instruction::isCast(Opcode: BC->Opcode)) { |
| 1729 | I = CastInst::Create((Instruction::CastOps)BC->Opcode, S: Ops[0], |
| 1730 | Ty: BC->getType(), Name: "constexpr" , InsertBefore: InsertBB); |
| 1731 | } else if (Instruction::isUnaryOp(Opcode: BC->Opcode)) { |
| 1732 | I = UnaryOperator::Create(Op: (Instruction::UnaryOps)BC->Opcode, S: Ops[0], |
| 1733 | Name: "constexpr" , InsertBefore: InsertBB); |
| 1734 | } else if (Instruction::isBinaryOp(Opcode: BC->Opcode)) { |
| 1735 | I = BinaryOperator::Create(Op: (Instruction::BinaryOps)BC->Opcode, S1: Ops[0], |
| 1736 | S2: Ops[1], Name: "constexpr" , InsertBefore: InsertBB); |
| 1737 | if (isa<OverflowingBinaryOperator>(Val: I)) { |
| 1738 | if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap) |
| 1739 | I->setHasNoSignedWrap(); |
| 1740 | if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap) |
| 1741 | I->setHasNoUnsignedWrap(); |
| 1742 | } |
| 1743 | if (isa<PossiblyExactOperator>(Val: I) && |
| 1744 | (BC->Flags & PossiblyExactOperator::IsExact)) |
| 1745 | I->setIsExact(); |
| 1746 | } else { |
| 1747 | switch (BC->Opcode) { |
| 1748 | case BitcodeConstant::ConstantVectorOpcode: { |
| 1749 | Type *IdxTy = Type::getInt32Ty(C&: BC->getContext()); |
| 1750 | Value *V = PoisonValue::get(T: BC->getType()); |
| 1751 | for (auto Pair : enumerate(First&: Ops)) { |
| 1752 | Value *Idx = ConstantInt::get(Ty: IdxTy, V: Pair.index()); |
| 1753 | V = InsertElementInst::Create(Vec: V, NewElt: Pair.value(), Idx, NameStr: "constexpr.ins" , |
| 1754 | InsertBefore: InsertBB); |
| 1755 | } |
| 1756 | I = cast<Instruction>(Val: V); |
| 1757 | break; |
| 1758 | } |
| 1759 | case BitcodeConstant::ConstantStructOpcode: |
| 1760 | case BitcodeConstant::ConstantArrayOpcode: { |
| 1761 | Value *V = PoisonValue::get(T: BC->getType()); |
| 1762 | for (auto Pair : enumerate(First&: Ops)) |
| 1763 | V = InsertValueInst::Create(Agg: V, Val: Pair.value(), Idxs: Pair.index(), |
| 1764 | NameStr: "constexpr.ins" , InsertBefore: InsertBB); |
| 1765 | I = cast<Instruction>(Val: V); |
| 1766 | break; |
| 1767 | } |
| 1768 | case Instruction::ICmp: |
| 1769 | case Instruction::FCmp: |
| 1770 | I = CmpInst::Create(Op: (Instruction::OtherOps)BC->Opcode, |
| 1771 | Pred: (CmpInst::Predicate)BC->Flags, S1: Ops[0], S2: Ops[1], |
| 1772 | Name: "constexpr" , InsertBefore: InsertBB); |
| 1773 | break; |
| 1774 | case Instruction::GetElementPtr: |
| 1775 | I = GetElementPtrInst::Create(PointeeType: BC->SrcElemTy, Ptr: Ops[0], |
| 1776 | IdxList: ArrayRef(Ops).drop_front(), NameStr: "constexpr" , |
| 1777 | InsertBefore: InsertBB); |
| 1778 | cast<GetElementPtrInst>(Val: I)->setNoWrapFlags(toGEPNoWrapFlags(Flags: BC->Flags)); |
| 1779 | break; |
| 1780 | case Instruction::Select: |
| 1781 | I = SelectInst::Create(C: Ops[0], S1: Ops[1], S2: Ops[2], NameStr: "constexpr" , InsertBefore: InsertBB); |
| 1782 | break; |
| 1783 | case Instruction::ExtractElement: |
| 1784 | I = ExtractElementInst::Create(Vec: Ops[0], Idx: Ops[1], NameStr: "constexpr" , InsertBefore: InsertBB); |
| 1785 | break; |
| 1786 | case Instruction::InsertElement: |
| 1787 | I = InsertElementInst::Create(Vec: Ops[0], NewElt: Ops[1], Idx: Ops[2], NameStr: "constexpr" , |
| 1788 | InsertBefore: InsertBB); |
| 1789 | break; |
| 1790 | case Instruction::ShuffleVector: |
| 1791 | I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr" , |
| 1792 | InsertBB); |
| 1793 | break; |
| 1794 | default: |
| 1795 | llvm_unreachable("Unhandled bitcode constant" ); |
| 1796 | } |
| 1797 | } |
| 1798 | |
| 1799 | MaterializedValues.insert(KV: {ValID, I}); |
| 1800 | Worklist.pop_back(); |
| 1801 | } |
| 1802 | |
| 1803 | return MaterializedValues[StartValID]; |
| 1804 | } |
| 1805 | |
| 1806 | Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) { |
| 1807 | Expected<Value *> MaybeV = materializeValue(StartValID: ID, /* InsertBB */ nullptr); |
| 1808 | if (!MaybeV) |
| 1809 | return MaybeV.takeError(); |
| 1810 | |
| 1811 | // Result must be Constant if InsertBB is nullptr. |
| 1812 | return cast<Constant>(Val: MaybeV.get()); |
| 1813 | } |
| 1814 | |
| 1815 | StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, |
| 1816 | StringRef Name) { |
| 1817 | auto *Ret = StructType::create(Context, Name); |
| 1818 | IdentifiedStructTypes.push_back(x: Ret); |
| 1819 | return Ret; |
| 1820 | } |
| 1821 | |
| 1822 | StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { |
| 1823 | auto *Ret = StructType::create(Context); |
| 1824 | IdentifiedStructTypes.push_back(x: Ret); |
| 1825 | return Ret; |
| 1826 | } |
| 1827 | |
| 1828 | //===----------------------------------------------------------------------===// |
| 1829 | // Functions for parsing blocks from the bitcode file |
| 1830 | //===----------------------------------------------------------------------===// |
| 1831 | |
| 1832 | static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { |
| 1833 | switch (Val) { |
| 1834 | case Attribute::EndAttrKinds: |
| 1835 | case Attribute::EmptyKey: |
| 1836 | case Attribute::TombstoneKey: |
| 1837 | llvm_unreachable("Synthetic enumerators which should never get here" ); |
| 1838 | |
| 1839 | case Attribute::None: return 0; |
| 1840 | case Attribute::ZExt: return 1 << 0; |
| 1841 | case Attribute::SExt: return 1 << 1; |
| 1842 | case Attribute::NoReturn: return 1 << 2; |
| 1843 | case Attribute::InReg: return 1 << 3; |
| 1844 | case Attribute::StructRet: return 1 << 4; |
| 1845 | case Attribute::NoUnwind: return 1 << 5; |
| 1846 | case Attribute::NoAlias: return 1 << 6; |
| 1847 | case Attribute::ByVal: return 1 << 7; |
| 1848 | case Attribute::Nest: return 1 << 8; |
| 1849 | case Attribute::ReadNone: return 1 << 9; |
| 1850 | case Attribute::ReadOnly: return 1 << 10; |
| 1851 | case Attribute::NoInline: return 1 << 11; |
| 1852 | case Attribute::AlwaysInline: return 1 << 12; |
| 1853 | case Attribute::OptimizeForSize: return 1 << 13; |
| 1854 | case Attribute::StackProtect: return 1 << 14; |
| 1855 | case Attribute::StackProtectReq: return 1 << 15; |
| 1856 | case Attribute::Alignment: return 31 << 16; |
| 1857 | // 1ULL << 21 is NoCapture, which is upgraded separately. |
| 1858 | case Attribute::NoRedZone: return 1 << 22; |
| 1859 | case Attribute::NoImplicitFloat: return 1 << 23; |
| 1860 | case Attribute::Naked: return 1 << 24; |
| 1861 | case Attribute::InlineHint: return 1 << 25; |
| 1862 | case Attribute::StackAlignment: return 7 << 26; |
| 1863 | case Attribute::ReturnsTwice: return 1 << 29; |
| 1864 | case Attribute::UWTable: return 1 << 30; |
| 1865 | case Attribute::NonLazyBind: return 1U << 31; |
| 1866 | case Attribute::SanitizeAddress: return 1ULL << 32; |
| 1867 | case Attribute::MinSize: return 1ULL << 33; |
| 1868 | case Attribute::NoDuplicate: return 1ULL << 34; |
| 1869 | case Attribute::StackProtectStrong: return 1ULL << 35; |
| 1870 | case Attribute::SanitizeThread: return 1ULL << 36; |
| 1871 | case Attribute::SanitizeMemory: return 1ULL << 37; |
| 1872 | case Attribute::NoBuiltin: return 1ULL << 38; |
| 1873 | case Attribute::Returned: return 1ULL << 39; |
| 1874 | case Attribute::Cold: return 1ULL << 40; |
| 1875 | case Attribute::Builtin: return 1ULL << 41; |
| 1876 | case Attribute::OptimizeNone: return 1ULL << 42; |
| 1877 | case Attribute::InAlloca: return 1ULL << 43; |
| 1878 | case Attribute::NonNull: return 1ULL << 44; |
| 1879 | case Attribute::JumpTable: return 1ULL << 45; |
| 1880 | case Attribute::Convergent: return 1ULL << 46; |
| 1881 | case Attribute::SafeStack: return 1ULL << 47; |
| 1882 | case Attribute::NoRecurse: return 1ULL << 48; |
| 1883 | // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately. |
| 1884 | // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately. |
| 1885 | case Attribute::SwiftSelf: return 1ULL << 51; |
| 1886 | case Attribute::SwiftError: return 1ULL << 52; |
| 1887 | case Attribute::WriteOnly: return 1ULL << 53; |
| 1888 | case Attribute::Speculatable: return 1ULL << 54; |
| 1889 | case Attribute::StrictFP: return 1ULL << 55; |
| 1890 | case Attribute::SanitizeHWAddress: return 1ULL << 56; |
| 1891 | case Attribute::NoCfCheck: return 1ULL << 57; |
| 1892 | case Attribute::OptForFuzzing: return 1ULL << 58; |
| 1893 | case Attribute::ShadowCallStack: return 1ULL << 59; |
| 1894 | case Attribute::SpeculativeLoadHardening: |
| 1895 | return 1ULL << 60; |
| 1896 | case Attribute::ImmArg: |
| 1897 | return 1ULL << 61; |
| 1898 | case Attribute::WillReturn: |
| 1899 | return 1ULL << 62; |
| 1900 | case Attribute::NoFree: |
| 1901 | return 1ULL << 63; |
| 1902 | default: |
| 1903 | // Other attributes are not supported in the raw format, |
| 1904 | // as we ran out of space. |
| 1905 | return 0; |
| 1906 | } |
| 1907 | llvm_unreachable("Unsupported attribute type" ); |
| 1908 | } |
| 1909 | |
| 1910 | static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { |
| 1911 | if (!Val) return; |
| 1912 | |
| 1913 | for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; |
| 1914 | I = Attribute::AttrKind(I + 1)) { |
| 1915 | if (uint64_t A = (Val & getRawAttributeMask(Val: I))) { |
| 1916 | if (I == Attribute::Alignment) |
| 1917 | B.addAlignmentAttr(Align: 1ULL << ((A >> 16) - 1)); |
| 1918 | else if (I == Attribute::StackAlignment) |
| 1919 | B.addStackAlignmentAttr(Align: 1ULL << ((A >> 26)-1)); |
| 1920 | else if (Attribute::isTypeAttrKind(Kind: I)) |
| 1921 | B.addTypeAttr(Kind: I, Ty: nullptr); // Type will be auto-upgraded. |
| 1922 | else |
| 1923 | B.addAttribute(Val: I); |
| 1924 | } |
| 1925 | } |
| 1926 | } |
| 1927 | |
| 1928 | /// This fills an AttrBuilder object with the LLVM attributes that have |
| 1929 | /// been decoded from the given integer. |
| 1930 | static void decodeLLVMAttributesForBitcode(AttrBuilder &B, |
| 1931 | uint64_t EncodedAttrs, |
| 1932 | uint64_t AttrIdx) { |
| 1933 | // The alignment is stored as a 16-bit raw value from bits 31--16. We shift |
| 1934 | // the bits above 31 down by 11 bits. |
| 1935 | unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; |
| 1936 | assert((!Alignment || isPowerOf2_32(Alignment)) && |
| 1937 | "Alignment must be a power of two." ); |
| 1938 | |
| 1939 | if (Alignment) |
| 1940 | B.addAlignmentAttr(Align: Alignment); |
| 1941 | |
| 1942 | uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | |
| 1943 | (EncodedAttrs & 0xffff); |
| 1944 | |
| 1945 | if (AttrIdx == AttributeList::FunctionIndex) { |
| 1946 | // Upgrade old memory attributes. |
| 1947 | MemoryEffects ME = MemoryEffects::unknown(); |
| 1948 | if (Attrs & (1ULL << 9)) { |
| 1949 | // ReadNone |
| 1950 | Attrs &= ~(1ULL << 9); |
| 1951 | ME &= MemoryEffects::none(); |
| 1952 | } |
| 1953 | if (Attrs & (1ULL << 10)) { |
| 1954 | // ReadOnly |
| 1955 | Attrs &= ~(1ULL << 10); |
| 1956 | ME &= MemoryEffects::readOnly(); |
| 1957 | } |
| 1958 | if (Attrs & (1ULL << 49)) { |
| 1959 | // InaccessibleMemOnly |
| 1960 | Attrs &= ~(1ULL << 49); |
| 1961 | ME &= MemoryEffects::inaccessibleMemOnly(); |
| 1962 | } |
| 1963 | if (Attrs & (1ULL << 50)) { |
| 1964 | // InaccessibleMemOrArgMemOnly |
| 1965 | Attrs &= ~(1ULL << 50); |
| 1966 | ME &= MemoryEffects::inaccessibleOrArgMemOnly(); |
| 1967 | } |
| 1968 | if (Attrs & (1ULL << 53)) { |
| 1969 | // WriteOnly |
| 1970 | Attrs &= ~(1ULL << 53); |
| 1971 | ME &= MemoryEffects::writeOnly(); |
| 1972 | } |
| 1973 | if (ME != MemoryEffects::unknown()) |
| 1974 | B.addMemoryAttr(ME); |
| 1975 | } |
| 1976 | |
| 1977 | // Upgrade nocapture to captures(none). |
| 1978 | if (Attrs & (1ULL << 21)) { |
| 1979 | Attrs &= ~(1ULL << 21); |
| 1980 | B.addCapturesAttr(CI: CaptureInfo::none()); |
| 1981 | } |
| 1982 | |
| 1983 | addRawAttributeValue(B, Val: Attrs); |
| 1984 | } |
| 1985 | |
| 1986 | Error BitcodeReader::parseAttributeBlock() { |
| 1987 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::PARAMATTR_BLOCK_ID)) |
| 1988 | return Err; |
| 1989 | |
| 1990 | if (!MAttributes.empty()) |
| 1991 | return error(Message: "Invalid multiple blocks" ); |
| 1992 | |
| 1993 | SmallVector<uint64_t, 64> Record; |
| 1994 | |
| 1995 | SmallVector<AttributeList, 8> Attrs; |
| 1996 | |
| 1997 | // Read all the records. |
| 1998 | while (true) { |
| 1999 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 2000 | if (!MaybeEntry) |
| 2001 | return MaybeEntry.takeError(); |
| 2002 | BitstreamEntry Entry = MaybeEntry.get(); |
| 2003 | |
| 2004 | switch (Entry.Kind) { |
| 2005 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 2006 | case BitstreamEntry::Error: |
| 2007 | return error(Message: "Malformed block" ); |
| 2008 | case BitstreamEntry::EndBlock: |
| 2009 | return Error::success(); |
| 2010 | case BitstreamEntry::Record: |
| 2011 | // The interesting case. |
| 2012 | break; |
| 2013 | } |
| 2014 | |
| 2015 | // Read a record. |
| 2016 | Record.clear(); |
| 2017 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 2018 | if (!MaybeRecord) |
| 2019 | return MaybeRecord.takeError(); |
| 2020 | switch (MaybeRecord.get()) { |
| 2021 | default: // Default behavior: ignore. |
| 2022 | break; |
| 2023 | case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] |
| 2024 | // Deprecated, but still needed to read old bitcode files. |
| 2025 | if (Record.size() & 1) |
| 2026 | return error(Message: "Invalid parameter attribute record" ); |
| 2027 | |
| 2028 | for (unsigned i = 0, e = Record.size(); i != e; i += 2) { |
| 2029 | AttrBuilder B(Context); |
| 2030 | decodeLLVMAttributesForBitcode(B, EncodedAttrs: Record[i+1], AttrIdx: Record[i]); |
| 2031 | Attrs.push_back(Elt: AttributeList::get(C&: Context, Index: Record[i], B)); |
| 2032 | } |
| 2033 | |
| 2034 | MAttributes.push_back(x: AttributeList::get(C&: Context, Attrs)); |
| 2035 | Attrs.clear(); |
| 2036 | break; |
| 2037 | case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] |
| 2038 | for (uint64_t Val : Record) |
| 2039 | Attrs.push_back(Elt: MAttributeGroups[Val]); |
| 2040 | |
| 2041 | MAttributes.push_back(x: AttributeList::get(C&: Context, Attrs)); |
| 2042 | Attrs.clear(); |
| 2043 | break; |
| 2044 | } |
| 2045 | } |
| 2046 | } |
| 2047 | |
| 2048 | // Returns Attribute::None on unrecognized codes. |
| 2049 | static Attribute::AttrKind getAttrFromCode(uint64_t Code) { |
| 2050 | switch (Code) { |
| 2051 | default: |
| 2052 | return Attribute::None; |
| 2053 | case bitc::ATTR_KIND_ALIGNMENT: |
| 2054 | return Attribute::Alignment; |
| 2055 | case bitc::ATTR_KIND_ALWAYS_INLINE: |
| 2056 | return Attribute::AlwaysInline; |
| 2057 | case bitc::ATTR_KIND_BUILTIN: |
| 2058 | return Attribute::Builtin; |
| 2059 | case bitc::ATTR_KIND_BY_VAL: |
| 2060 | return Attribute::ByVal; |
| 2061 | case bitc::ATTR_KIND_IN_ALLOCA: |
| 2062 | return Attribute::InAlloca; |
| 2063 | case bitc::ATTR_KIND_COLD: |
| 2064 | return Attribute::Cold; |
| 2065 | case bitc::ATTR_KIND_CONVERGENT: |
| 2066 | return Attribute::Convergent; |
| 2067 | case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION: |
| 2068 | return Attribute::DisableSanitizerInstrumentation; |
| 2069 | case bitc::ATTR_KIND_ELEMENTTYPE: |
| 2070 | return Attribute::ElementType; |
| 2071 | case bitc::ATTR_KIND_FNRETTHUNK_EXTERN: |
| 2072 | return Attribute::FnRetThunkExtern; |
| 2073 | case bitc::ATTR_KIND_INLINE_HINT: |
| 2074 | return Attribute::InlineHint; |
| 2075 | case bitc::ATTR_KIND_IN_REG: |
| 2076 | return Attribute::InReg; |
| 2077 | case bitc::ATTR_KIND_JUMP_TABLE: |
| 2078 | return Attribute::JumpTable; |
| 2079 | case bitc::ATTR_KIND_MEMORY: |
| 2080 | return Attribute::Memory; |
| 2081 | case bitc::ATTR_KIND_NOFPCLASS: |
| 2082 | return Attribute::NoFPClass; |
| 2083 | case bitc::ATTR_KIND_MIN_SIZE: |
| 2084 | return Attribute::MinSize; |
| 2085 | case bitc::ATTR_KIND_NAKED: |
| 2086 | return Attribute::Naked; |
| 2087 | case bitc::ATTR_KIND_NEST: |
| 2088 | return Attribute::Nest; |
| 2089 | case bitc::ATTR_KIND_NO_ALIAS: |
| 2090 | return Attribute::NoAlias; |
| 2091 | case bitc::ATTR_KIND_NO_BUILTIN: |
| 2092 | return Attribute::NoBuiltin; |
| 2093 | case bitc::ATTR_KIND_NO_CALLBACK: |
| 2094 | return Attribute::NoCallback; |
| 2095 | case bitc::ATTR_KIND_NO_DIVERGENCE_SOURCE: |
| 2096 | return Attribute::NoDivergenceSource; |
| 2097 | case bitc::ATTR_KIND_NO_DUPLICATE: |
| 2098 | return Attribute::NoDuplicate; |
| 2099 | case bitc::ATTR_KIND_NOFREE: |
| 2100 | return Attribute::NoFree; |
| 2101 | case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: |
| 2102 | return Attribute::NoImplicitFloat; |
| 2103 | case bitc::ATTR_KIND_NO_INLINE: |
| 2104 | return Attribute::NoInline; |
| 2105 | case bitc::ATTR_KIND_NO_RECURSE: |
| 2106 | return Attribute::NoRecurse; |
| 2107 | case bitc::ATTR_KIND_NO_MERGE: |
| 2108 | return Attribute::NoMerge; |
| 2109 | case bitc::ATTR_KIND_NON_LAZY_BIND: |
| 2110 | return Attribute::NonLazyBind; |
| 2111 | case bitc::ATTR_KIND_NON_NULL: |
| 2112 | return Attribute::NonNull; |
| 2113 | case bitc::ATTR_KIND_DEREFERENCEABLE: |
| 2114 | return Attribute::Dereferenceable; |
| 2115 | case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: |
| 2116 | return Attribute::DereferenceableOrNull; |
| 2117 | case bitc::ATTR_KIND_ALLOC_ALIGN: |
| 2118 | return Attribute::AllocAlign; |
| 2119 | case bitc::ATTR_KIND_ALLOC_KIND: |
| 2120 | return Attribute::AllocKind; |
| 2121 | case bitc::ATTR_KIND_ALLOC_SIZE: |
| 2122 | return Attribute::AllocSize; |
| 2123 | case bitc::ATTR_KIND_ALLOCATED_POINTER: |
| 2124 | return Attribute::AllocatedPointer; |
| 2125 | case bitc::ATTR_KIND_NO_RED_ZONE: |
| 2126 | return Attribute::NoRedZone; |
| 2127 | case bitc::ATTR_KIND_NO_RETURN: |
| 2128 | return Attribute::NoReturn; |
| 2129 | case bitc::ATTR_KIND_NOSYNC: |
| 2130 | return Attribute::NoSync; |
| 2131 | case bitc::ATTR_KIND_NOCF_CHECK: |
| 2132 | return Attribute::NoCfCheck; |
| 2133 | case bitc::ATTR_KIND_NO_PROFILE: |
| 2134 | return Attribute::NoProfile; |
| 2135 | case bitc::ATTR_KIND_SKIP_PROFILE: |
| 2136 | return Attribute::SkipProfile; |
| 2137 | case bitc::ATTR_KIND_NO_UNWIND: |
| 2138 | return Attribute::NoUnwind; |
| 2139 | case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS: |
| 2140 | return Attribute::NoSanitizeBounds; |
| 2141 | case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE: |
| 2142 | return Attribute::NoSanitizeCoverage; |
| 2143 | case bitc::ATTR_KIND_NULL_POINTER_IS_VALID: |
| 2144 | return Attribute::NullPointerIsValid; |
| 2145 | case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING: |
| 2146 | return Attribute::OptimizeForDebugging; |
| 2147 | case bitc::ATTR_KIND_OPT_FOR_FUZZING: |
| 2148 | return Attribute::OptForFuzzing; |
| 2149 | case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: |
| 2150 | return Attribute::OptimizeForSize; |
| 2151 | case bitc::ATTR_KIND_OPTIMIZE_NONE: |
| 2152 | return Attribute::OptimizeNone; |
| 2153 | case bitc::ATTR_KIND_READ_NONE: |
| 2154 | return Attribute::ReadNone; |
| 2155 | case bitc::ATTR_KIND_READ_ONLY: |
| 2156 | return Attribute::ReadOnly; |
| 2157 | case bitc::ATTR_KIND_RETURNED: |
| 2158 | return Attribute::Returned; |
| 2159 | case bitc::ATTR_KIND_RETURNS_TWICE: |
| 2160 | return Attribute::ReturnsTwice; |
| 2161 | case bitc::ATTR_KIND_S_EXT: |
| 2162 | return Attribute::SExt; |
| 2163 | case bitc::ATTR_KIND_SPECULATABLE: |
| 2164 | return Attribute::Speculatable; |
| 2165 | case bitc::ATTR_KIND_STACK_ALIGNMENT: |
| 2166 | return Attribute::StackAlignment; |
| 2167 | case bitc::ATTR_KIND_STACK_PROTECT: |
| 2168 | return Attribute::StackProtect; |
| 2169 | case bitc::ATTR_KIND_STACK_PROTECT_REQ: |
| 2170 | return Attribute::StackProtectReq; |
| 2171 | case bitc::ATTR_KIND_STACK_PROTECT_STRONG: |
| 2172 | return Attribute::StackProtectStrong; |
| 2173 | case bitc::ATTR_KIND_SAFESTACK: |
| 2174 | return Attribute::SafeStack; |
| 2175 | case bitc::ATTR_KIND_SHADOWCALLSTACK: |
| 2176 | return Attribute::ShadowCallStack; |
| 2177 | case bitc::ATTR_KIND_STRICT_FP: |
| 2178 | return Attribute::StrictFP; |
| 2179 | case bitc::ATTR_KIND_STRUCT_RET: |
| 2180 | return Attribute::StructRet; |
| 2181 | case bitc::ATTR_KIND_SANITIZE_ADDRESS: |
| 2182 | return Attribute::SanitizeAddress; |
| 2183 | case bitc::ATTR_KIND_SANITIZE_HWADDRESS: |
| 2184 | return Attribute::SanitizeHWAddress; |
| 2185 | case bitc::ATTR_KIND_SANITIZE_THREAD: |
| 2186 | return Attribute::SanitizeThread; |
| 2187 | case bitc::ATTR_KIND_SANITIZE_TYPE: |
| 2188 | return Attribute::SanitizeType; |
| 2189 | case bitc::ATTR_KIND_SANITIZE_MEMORY: |
| 2190 | return Attribute::SanitizeMemory; |
| 2191 | case bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY: |
| 2192 | return Attribute::SanitizeNumericalStability; |
| 2193 | case bitc::ATTR_KIND_SANITIZE_REALTIME: |
| 2194 | return Attribute::SanitizeRealtime; |
| 2195 | case bitc::ATTR_KIND_SANITIZE_REALTIME_BLOCKING: |
| 2196 | return Attribute::SanitizeRealtimeBlocking; |
| 2197 | case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING: |
| 2198 | return Attribute::SpeculativeLoadHardening; |
| 2199 | case bitc::ATTR_KIND_SWIFT_ERROR: |
| 2200 | return Attribute::SwiftError; |
| 2201 | case bitc::ATTR_KIND_SWIFT_SELF: |
| 2202 | return Attribute::SwiftSelf; |
| 2203 | case bitc::ATTR_KIND_SWIFT_ASYNC: |
| 2204 | return Attribute::SwiftAsync; |
| 2205 | case bitc::ATTR_KIND_UW_TABLE: |
| 2206 | return Attribute::UWTable; |
| 2207 | case bitc::ATTR_KIND_VSCALE_RANGE: |
| 2208 | return Attribute::VScaleRange; |
| 2209 | case bitc::ATTR_KIND_WILLRETURN: |
| 2210 | return Attribute::WillReturn; |
| 2211 | case bitc::ATTR_KIND_WRITEONLY: |
| 2212 | return Attribute::WriteOnly; |
| 2213 | case bitc::ATTR_KIND_Z_EXT: |
| 2214 | return Attribute::ZExt; |
| 2215 | case bitc::ATTR_KIND_IMMARG: |
| 2216 | return Attribute::ImmArg; |
| 2217 | case bitc::ATTR_KIND_SANITIZE_MEMTAG: |
| 2218 | return Attribute::SanitizeMemTag; |
| 2219 | case bitc::ATTR_KIND_PREALLOCATED: |
| 2220 | return Attribute::Preallocated; |
| 2221 | case bitc::ATTR_KIND_NOUNDEF: |
| 2222 | return Attribute::NoUndef; |
| 2223 | case bitc::ATTR_KIND_BYREF: |
| 2224 | return Attribute::ByRef; |
| 2225 | case bitc::ATTR_KIND_MUSTPROGRESS: |
| 2226 | return Attribute::MustProgress; |
| 2227 | case bitc::ATTR_KIND_HOT: |
| 2228 | return Attribute::Hot; |
| 2229 | case bitc::ATTR_KIND_PRESPLIT_COROUTINE: |
| 2230 | return Attribute::PresplitCoroutine; |
| 2231 | case bitc::ATTR_KIND_WRITABLE: |
| 2232 | return Attribute::Writable; |
| 2233 | case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE: |
| 2234 | return Attribute::CoroDestroyOnlyWhenComplete; |
| 2235 | case bitc::ATTR_KIND_DEAD_ON_UNWIND: |
| 2236 | return Attribute::DeadOnUnwind; |
| 2237 | case bitc::ATTR_KIND_RANGE: |
| 2238 | return Attribute::Range; |
| 2239 | case bitc::ATTR_KIND_INITIALIZES: |
| 2240 | return Attribute::Initializes; |
| 2241 | case bitc::ATTR_KIND_CORO_ELIDE_SAFE: |
| 2242 | return Attribute::CoroElideSafe; |
| 2243 | case bitc::ATTR_KIND_NO_EXT: |
| 2244 | return Attribute::NoExt; |
| 2245 | case bitc::ATTR_KIND_CAPTURES: |
| 2246 | return Attribute::Captures; |
| 2247 | case bitc::ATTR_KIND_DEAD_ON_RETURN: |
| 2248 | return Attribute::DeadOnReturn; |
| 2249 | } |
| 2250 | } |
| 2251 | |
| 2252 | Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, |
| 2253 | MaybeAlign &Alignment) { |
| 2254 | // Note: Alignment in bitcode files is incremented by 1, so that zero |
| 2255 | // can be used for default alignment. |
| 2256 | if (Exponent > Value::MaxAlignmentExponent + 1) |
| 2257 | return error(Message: "Invalid alignment value" ); |
| 2258 | Alignment = decodeMaybeAlign(Value: Exponent); |
| 2259 | return Error::success(); |
| 2260 | } |
| 2261 | |
| 2262 | Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { |
| 2263 | *Kind = getAttrFromCode(Code); |
| 2264 | if (*Kind == Attribute::None) |
| 2265 | return error(Message: "Unknown attribute kind (" + Twine(Code) + ")" ); |
| 2266 | return Error::success(); |
| 2267 | } |
| 2268 | |
| 2269 | static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) { |
| 2270 | switch (EncodedKind) { |
| 2271 | case bitc::ATTR_KIND_READ_NONE: |
| 2272 | ME &= MemoryEffects::none(); |
| 2273 | return true; |
| 2274 | case bitc::ATTR_KIND_READ_ONLY: |
| 2275 | ME &= MemoryEffects::readOnly(); |
| 2276 | return true; |
| 2277 | case bitc::ATTR_KIND_WRITEONLY: |
| 2278 | ME &= MemoryEffects::writeOnly(); |
| 2279 | return true; |
| 2280 | case bitc::ATTR_KIND_ARGMEMONLY: |
| 2281 | ME &= MemoryEffects::argMemOnly(); |
| 2282 | return true; |
| 2283 | case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: |
| 2284 | ME &= MemoryEffects::inaccessibleMemOnly(); |
| 2285 | return true; |
| 2286 | case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: |
| 2287 | ME &= MemoryEffects::inaccessibleOrArgMemOnly(); |
| 2288 | return true; |
| 2289 | default: |
| 2290 | return false; |
| 2291 | } |
| 2292 | } |
| 2293 | |
| 2294 | Error BitcodeReader::parseAttributeGroupBlock() { |
| 2295 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::PARAMATTR_GROUP_BLOCK_ID)) |
| 2296 | return Err; |
| 2297 | |
| 2298 | if (!MAttributeGroups.empty()) |
| 2299 | return error(Message: "Invalid multiple blocks" ); |
| 2300 | |
| 2301 | SmallVector<uint64_t, 64> Record; |
| 2302 | |
| 2303 | // Read all the records. |
| 2304 | while (true) { |
| 2305 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 2306 | if (!MaybeEntry) |
| 2307 | return MaybeEntry.takeError(); |
| 2308 | BitstreamEntry Entry = MaybeEntry.get(); |
| 2309 | |
| 2310 | switch (Entry.Kind) { |
| 2311 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 2312 | case BitstreamEntry::Error: |
| 2313 | return error(Message: "Malformed block" ); |
| 2314 | case BitstreamEntry::EndBlock: |
| 2315 | return Error::success(); |
| 2316 | case BitstreamEntry::Record: |
| 2317 | // The interesting case. |
| 2318 | break; |
| 2319 | } |
| 2320 | |
| 2321 | // Read a record. |
| 2322 | Record.clear(); |
| 2323 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 2324 | if (!MaybeRecord) |
| 2325 | return MaybeRecord.takeError(); |
| 2326 | switch (MaybeRecord.get()) { |
| 2327 | default: // Default behavior: ignore. |
| 2328 | break; |
| 2329 | case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] |
| 2330 | if (Record.size() < 3) |
| 2331 | return error(Message: "Invalid grp record" ); |
| 2332 | |
| 2333 | uint64_t GrpID = Record[0]; |
| 2334 | uint64_t Idx = Record[1]; // Index of the object this attribute refers to. |
| 2335 | |
| 2336 | AttrBuilder B(Context); |
| 2337 | MemoryEffects ME = MemoryEffects::unknown(); |
| 2338 | for (unsigned i = 2, e = Record.size(); i != e; ++i) { |
| 2339 | if (Record[i] == 0) { // Enum attribute |
| 2340 | Attribute::AttrKind Kind; |
| 2341 | uint64_t EncodedKind = Record[++i]; |
| 2342 | if (Idx == AttributeList::FunctionIndex && |
| 2343 | upgradeOldMemoryAttribute(ME, EncodedKind)) |
| 2344 | continue; |
| 2345 | |
| 2346 | if (EncodedKind == bitc::ATTR_KIND_NO_CAPTURE) { |
| 2347 | B.addCapturesAttr(CI: CaptureInfo::none()); |
| 2348 | continue; |
| 2349 | } |
| 2350 | |
| 2351 | if (Error Err = parseAttrKind(Code: EncodedKind, Kind: &Kind)) |
| 2352 | return Err; |
| 2353 | |
| 2354 | // Upgrade old-style byval attribute to one with a type, even if it's |
| 2355 | // nullptr. We will have to insert the real type when we associate |
| 2356 | // this AttributeList with a function. |
| 2357 | if (Kind == Attribute::ByVal) |
| 2358 | B.addByValAttr(Ty: nullptr); |
| 2359 | else if (Kind == Attribute::StructRet) |
| 2360 | B.addStructRetAttr(Ty: nullptr); |
| 2361 | else if (Kind == Attribute::InAlloca) |
| 2362 | B.addInAllocaAttr(Ty: nullptr); |
| 2363 | else if (Kind == Attribute::UWTable) |
| 2364 | B.addUWTableAttr(Kind: UWTableKind::Default); |
| 2365 | else if (Attribute::isEnumAttrKind(Kind)) |
| 2366 | B.addAttribute(Val: Kind); |
| 2367 | else |
| 2368 | return error(Message: "Not an enum attribute" ); |
| 2369 | } else if (Record[i] == 1) { // Integer attribute |
| 2370 | Attribute::AttrKind Kind; |
| 2371 | if (Error Err = parseAttrKind(Code: Record[++i], Kind: &Kind)) |
| 2372 | return Err; |
| 2373 | if (!Attribute::isIntAttrKind(Kind)) |
| 2374 | return error(Message: "Not an int attribute" ); |
| 2375 | if (Kind == Attribute::Alignment) |
| 2376 | B.addAlignmentAttr(Align: Record[++i]); |
| 2377 | else if (Kind == Attribute::StackAlignment) |
| 2378 | B.addStackAlignmentAttr(Align: Record[++i]); |
| 2379 | else if (Kind == Attribute::Dereferenceable) |
| 2380 | B.addDereferenceableAttr(Bytes: Record[++i]); |
| 2381 | else if (Kind == Attribute::DereferenceableOrNull) |
| 2382 | B.addDereferenceableOrNullAttr(Bytes: Record[++i]); |
| 2383 | else if (Kind == Attribute::AllocSize) |
| 2384 | B.addAllocSizeAttrFromRawRepr(RawAllocSizeRepr: Record[++i]); |
| 2385 | else if (Kind == Attribute::VScaleRange) |
| 2386 | B.addVScaleRangeAttrFromRawRepr(RawVScaleRangeRepr: Record[++i]); |
| 2387 | else if (Kind == Attribute::UWTable) |
| 2388 | B.addUWTableAttr(Kind: UWTableKind(Record[++i])); |
| 2389 | else if (Kind == Attribute::AllocKind) |
| 2390 | B.addAllocKindAttr(Kind: static_cast<AllocFnKind>(Record[++i])); |
| 2391 | else if (Kind == Attribute::Memory) { |
| 2392 | uint64_t EncodedME = Record[++i]; |
| 2393 | const uint8_t Version = (EncodedME >> 56); |
| 2394 | if (Version == 0) { |
| 2395 | // Errno memory location was previously encompassed into default |
| 2396 | // memory. Ensure this is taken into account while reconstructing |
| 2397 | // the memory attribute prior to its introduction. |
| 2398 | ModRefInfo ArgMem = ModRefInfo((EncodedME >> 0) & 3); |
| 2399 | ModRefInfo InaccessibleMem = ModRefInfo((EncodedME >> 2) & 3); |
| 2400 | ModRefInfo OtherMem = ModRefInfo((EncodedME >> 4) & 3); |
| 2401 | auto ME = MemoryEffects::inaccessibleMemOnly(MR: InaccessibleMem) | |
| 2402 | MemoryEffects::argMemOnly(MR: ArgMem) | |
| 2403 | MemoryEffects::errnoMemOnly(MR: OtherMem) | |
| 2404 | MemoryEffects::otherMemOnly(MR: OtherMem); |
| 2405 | B.addMemoryAttr(ME); |
| 2406 | } else { |
| 2407 | // Construct the memory attribute directly from the encoded base |
| 2408 | // on newer versions. |
| 2409 | B.addMemoryAttr(ME: MemoryEffects::createFromIntValue( |
| 2410 | Data: EncodedME & 0x00FFFFFFFFFFFFFFULL)); |
| 2411 | } |
| 2412 | } else if (Kind == Attribute::Captures) |
| 2413 | B.addCapturesAttr(CI: CaptureInfo::createFromIntValue(Data: Record[++i])); |
| 2414 | else if (Kind == Attribute::NoFPClass) |
| 2415 | B.addNoFPClassAttr( |
| 2416 | NoFPClassMask: static_cast<FPClassTest>(Record[++i] & fcAllFlags)); |
| 2417 | } else if (Record[i] == 3 || Record[i] == 4) { // String attribute |
| 2418 | bool HasValue = (Record[i++] == 4); |
| 2419 | SmallString<64> KindStr; |
| 2420 | SmallString<64> ValStr; |
| 2421 | |
| 2422 | while (Record[i] != 0 && i != e) |
| 2423 | KindStr += Record[i++]; |
| 2424 | assert(Record[i] == 0 && "Kind string not null terminated" ); |
| 2425 | |
| 2426 | if (HasValue) { |
| 2427 | // Has a value associated with it. |
| 2428 | ++i; // Skip the '0' that terminates the "kind" string. |
| 2429 | while (Record[i] != 0 && i != e) |
| 2430 | ValStr += Record[i++]; |
| 2431 | assert(Record[i] == 0 && "Value string not null terminated" ); |
| 2432 | } |
| 2433 | |
| 2434 | B.addAttribute(A: KindStr.str(), V: ValStr.str()); |
| 2435 | } else if (Record[i] == 5 || Record[i] == 6) { |
| 2436 | bool HasType = Record[i] == 6; |
| 2437 | Attribute::AttrKind Kind; |
| 2438 | if (Error Err = parseAttrKind(Code: Record[++i], Kind: &Kind)) |
| 2439 | return Err; |
| 2440 | if (!Attribute::isTypeAttrKind(Kind)) |
| 2441 | return error(Message: "Not a type attribute" ); |
| 2442 | |
| 2443 | B.addTypeAttr(Kind, Ty: HasType ? getTypeByID(ID: Record[++i]) : nullptr); |
| 2444 | } else if (Record[i] == 7) { |
| 2445 | Attribute::AttrKind Kind; |
| 2446 | |
| 2447 | i++; |
| 2448 | if (Error Err = parseAttrKind(Code: Record[i++], Kind: &Kind)) |
| 2449 | return Err; |
| 2450 | if (!Attribute::isConstantRangeAttrKind(Kind)) |
| 2451 | return error(Message: "Not a ConstantRange attribute" ); |
| 2452 | |
| 2453 | Expected<ConstantRange> MaybeCR = |
| 2454 | readBitWidthAndConstantRange(Record, OpNum&: i); |
| 2455 | if (!MaybeCR) |
| 2456 | return MaybeCR.takeError(); |
| 2457 | i--; |
| 2458 | |
| 2459 | B.addConstantRangeAttr(Kind, CR: MaybeCR.get()); |
| 2460 | } else if (Record[i] == 8) { |
| 2461 | Attribute::AttrKind Kind; |
| 2462 | |
| 2463 | i++; |
| 2464 | if (Error Err = parseAttrKind(Code: Record[i++], Kind: &Kind)) |
| 2465 | return Err; |
| 2466 | if (!Attribute::isConstantRangeListAttrKind(Kind)) |
| 2467 | return error(Message: "Not a constant range list attribute" ); |
| 2468 | |
| 2469 | SmallVector<ConstantRange, 2> Val; |
| 2470 | if (i + 2 > e) |
| 2471 | return error(Message: "Too few records for constant range list" ); |
| 2472 | unsigned RangeSize = Record[i++]; |
| 2473 | unsigned BitWidth = Record[i++]; |
| 2474 | for (unsigned Idx = 0; Idx < RangeSize; ++Idx) { |
| 2475 | Expected<ConstantRange> MaybeCR = |
| 2476 | readConstantRange(Record, OpNum&: i, BitWidth); |
| 2477 | if (!MaybeCR) |
| 2478 | return MaybeCR.takeError(); |
| 2479 | Val.push_back(Elt: MaybeCR.get()); |
| 2480 | } |
| 2481 | i--; |
| 2482 | |
| 2483 | if (!ConstantRangeList::isOrderedRanges(RangesRef: Val)) |
| 2484 | return error(Message: "Invalid (unordered or overlapping) range list" ); |
| 2485 | B.addConstantRangeListAttr(Kind, Val); |
| 2486 | } else { |
| 2487 | return error(Message: "Invalid attribute group entry" ); |
| 2488 | } |
| 2489 | } |
| 2490 | |
| 2491 | if (ME != MemoryEffects::unknown()) |
| 2492 | B.addMemoryAttr(ME); |
| 2493 | |
| 2494 | UpgradeAttributes(B); |
| 2495 | MAttributeGroups[GrpID] = AttributeList::get(C&: Context, Index: Idx, B); |
| 2496 | break; |
| 2497 | } |
| 2498 | } |
| 2499 | } |
| 2500 | } |
| 2501 | |
| 2502 | Error BitcodeReader::parseTypeTable() { |
| 2503 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::TYPE_BLOCK_ID_NEW)) |
| 2504 | return Err; |
| 2505 | |
| 2506 | return parseTypeTableBody(); |
| 2507 | } |
| 2508 | |
| 2509 | Error BitcodeReader::parseTypeTableBody() { |
| 2510 | if (!TypeList.empty()) |
| 2511 | return error(Message: "Invalid multiple blocks" ); |
| 2512 | |
| 2513 | SmallVector<uint64_t, 64> Record; |
| 2514 | unsigned NumRecords = 0; |
| 2515 | |
| 2516 | SmallString<64> TypeName; |
| 2517 | |
| 2518 | // Read all the records for this type table. |
| 2519 | while (true) { |
| 2520 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 2521 | if (!MaybeEntry) |
| 2522 | return MaybeEntry.takeError(); |
| 2523 | BitstreamEntry Entry = MaybeEntry.get(); |
| 2524 | |
| 2525 | switch (Entry.Kind) { |
| 2526 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 2527 | case BitstreamEntry::Error: |
| 2528 | return error(Message: "Malformed block" ); |
| 2529 | case BitstreamEntry::EndBlock: |
| 2530 | if (NumRecords != TypeList.size()) |
| 2531 | return error(Message: "Malformed block" ); |
| 2532 | return Error::success(); |
| 2533 | case BitstreamEntry::Record: |
| 2534 | // The interesting case. |
| 2535 | break; |
| 2536 | } |
| 2537 | |
| 2538 | // Read a record. |
| 2539 | Record.clear(); |
| 2540 | Type *ResultTy = nullptr; |
| 2541 | SmallVector<unsigned> ContainedIDs; |
| 2542 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 2543 | if (!MaybeRecord) |
| 2544 | return MaybeRecord.takeError(); |
| 2545 | switch (MaybeRecord.get()) { |
| 2546 | default: |
| 2547 | return error(Message: "Invalid value" ); |
| 2548 | case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] |
| 2549 | // TYPE_CODE_NUMENTRY contains a count of the number of types in the |
| 2550 | // type list. This allows us to reserve space. |
| 2551 | if (Record.empty()) |
| 2552 | return error(Message: "Invalid numentry record" ); |
| 2553 | TypeList.resize(new_size: Record[0]); |
| 2554 | continue; |
| 2555 | case bitc::TYPE_CODE_VOID: // VOID |
| 2556 | ResultTy = Type::getVoidTy(C&: Context); |
| 2557 | break; |
| 2558 | case bitc::TYPE_CODE_HALF: // HALF |
| 2559 | ResultTy = Type::getHalfTy(C&: Context); |
| 2560 | break; |
| 2561 | case bitc::TYPE_CODE_BFLOAT: // BFLOAT |
| 2562 | ResultTy = Type::getBFloatTy(C&: Context); |
| 2563 | break; |
| 2564 | case bitc::TYPE_CODE_FLOAT: // FLOAT |
| 2565 | ResultTy = Type::getFloatTy(C&: Context); |
| 2566 | break; |
| 2567 | case bitc::TYPE_CODE_DOUBLE: // DOUBLE |
| 2568 | ResultTy = Type::getDoubleTy(C&: Context); |
| 2569 | break; |
| 2570 | case bitc::TYPE_CODE_X86_FP80: // X86_FP80 |
| 2571 | ResultTy = Type::getX86_FP80Ty(C&: Context); |
| 2572 | break; |
| 2573 | case bitc::TYPE_CODE_FP128: // FP128 |
| 2574 | ResultTy = Type::getFP128Ty(C&: Context); |
| 2575 | break; |
| 2576 | case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 |
| 2577 | ResultTy = Type::getPPC_FP128Ty(C&: Context); |
| 2578 | break; |
| 2579 | case bitc::TYPE_CODE_LABEL: // LABEL |
| 2580 | ResultTy = Type::getLabelTy(C&: Context); |
| 2581 | break; |
| 2582 | case bitc::TYPE_CODE_METADATA: // METADATA |
| 2583 | ResultTy = Type::getMetadataTy(C&: Context); |
| 2584 | break; |
| 2585 | case bitc::TYPE_CODE_X86_MMX: // X86_MMX |
| 2586 | // Deprecated: decodes as <1 x i64> |
| 2587 | ResultTy = |
| 2588 | llvm::FixedVectorType::get(ElementType: llvm::IntegerType::get(C&: Context, NumBits: 64), NumElts: 1); |
| 2589 | break; |
| 2590 | case bitc::TYPE_CODE_X86_AMX: // X86_AMX |
| 2591 | ResultTy = Type::getX86_AMXTy(C&: Context); |
| 2592 | break; |
| 2593 | case bitc::TYPE_CODE_TOKEN: // TOKEN |
| 2594 | ResultTy = Type::getTokenTy(C&: Context); |
| 2595 | break; |
| 2596 | case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] |
| 2597 | if (Record.empty()) |
| 2598 | return error(Message: "Invalid integer record" ); |
| 2599 | |
| 2600 | uint64_t NumBits = Record[0]; |
| 2601 | if (NumBits < IntegerType::MIN_INT_BITS || |
| 2602 | NumBits > IntegerType::MAX_INT_BITS) |
| 2603 | return error(Message: "Bitwidth for integer type out of range" ); |
| 2604 | ResultTy = IntegerType::get(C&: Context, NumBits); |
| 2605 | break; |
| 2606 | } |
| 2607 | case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or |
| 2608 | // [pointee type, address space] |
| 2609 | if (Record.empty()) |
| 2610 | return error(Message: "Invalid pointer record" ); |
| 2611 | unsigned AddressSpace = 0; |
| 2612 | if (Record.size() == 2) |
| 2613 | AddressSpace = Record[1]; |
| 2614 | ResultTy = getTypeByID(ID: Record[0]); |
| 2615 | if (!ResultTy || |
| 2616 | !PointerType::isValidElementType(ElemTy: ResultTy)) |
| 2617 | return error(Message: "Invalid type" ); |
| 2618 | ContainedIDs.push_back(Elt: Record[0]); |
| 2619 | ResultTy = PointerType::get(C&: ResultTy->getContext(), AddressSpace); |
| 2620 | break; |
| 2621 | } |
| 2622 | case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace] |
| 2623 | if (Record.size() != 1) |
| 2624 | return error(Message: "Invalid opaque pointer record" ); |
| 2625 | unsigned AddressSpace = Record[0]; |
| 2626 | ResultTy = PointerType::get(C&: Context, AddressSpace); |
| 2627 | break; |
| 2628 | } |
| 2629 | case bitc::TYPE_CODE_FUNCTION_OLD: { |
| 2630 | // Deprecated, but still needed to read old bitcode files. |
| 2631 | // FUNCTION: [vararg, attrid, retty, paramty x N] |
| 2632 | if (Record.size() < 3) |
| 2633 | return error(Message: "Invalid function record" ); |
| 2634 | SmallVector<Type*, 8> ArgTys; |
| 2635 | for (unsigned i = 3, e = Record.size(); i != e; ++i) { |
| 2636 | if (Type *T = getTypeByID(ID: Record[i])) |
| 2637 | ArgTys.push_back(Elt: T); |
| 2638 | else |
| 2639 | break; |
| 2640 | } |
| 2641 | |
| 2642 | ResultTy = getTypeByID(ID: Record[2]); |
| 2643 | if (!ResultTy || ArgTys.size() < Record.size()-3) |
| 2644 | return error(Message: "Invalid type" ); |
| 2645 | |
| 2646 | ContainedIDs.append(in_start: Record.begin() + 2, in_end: Record.end()); |
| 2647 | ResultTy = FunctionType::get(Result: ResultTy, Params: ArgTys, isVarArg: Record[0]); |
| 2648 | break; |
| 2649 | } |
| 2650 | case bitc::TYPE_CODE_FUNCTION: { |
| 2651 | // FUNCTION: [vararg, retty, paramty x N] |
| 2652 | if (Record.size() < 2) |
| 2653 | return error(Message: "Invalid function record" ); |
| 2654 | SmallVector<Type*, 8> ArgTys; |
| 2655 | for (unsigned i = 2, e = Record.size(); i != e; ++i) { |
| 2656 | if (Type *T = getTypeByID(ID: Record[i])) { |
| 2657 | if (!FunctionType::isValidArgumentType(ArgTy: T)) |
| 2658 | return error(Message: "Invalid function argument type" ); |
| 2659 | ArgTys.push_back(Elt: T); |
| 2660 | } |
| 2661 | else |
| 2662 | break; |
| 2663 | } |
| 2664 | |
| 2665 | ResultTy = getTypeByID(ID: Record[1]); |
| 2666 | if (!ResultTy || ArgTys.size() < Record.size()-2) |
| 2667 | return error(Message: "Invalid type" ); |
| 2668 | |
| 2669 | ContainedIDs.append(in_start: Record.begin() + 1, in_end: Record.end()); |
| 2670 | ResultTy = FunctionType::get(Result: ResultTy, Params: ArgTys, isVarArg: Record[0]); |
| 2671 | break; |
| 2672 | } |
| 2673 | case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] |
| 2674 | if (Record.empty()) |
| 2675 | return error(Message: "Invalid anon struct record" ); |
| 2676 | SmallVector<Type*, 8> EltTys; |
| 2677 | for (unsigned i = 1, e = Record.size(); i != e; ++i) { |
| 2678 | if (Type *T = getTypeByID(ID: Record[i])) |
| 2679 | EltTys.push_back(Elt: T); |
| 2680 | else |
| 2681 | break; |
| 2682 | } |
| 2683 | if (EltTys.size() != Record.size()-1) |
| 2684 | return error(Message: "Invalid type" ); |
| 2685 | ContainedIDs.append(in_start: Record.begin() + 1, in_end: Record.end()); |
| 2686 | ResultTy = StructType::get(Context, Elements: EltTys, isPacked: Record[0]); |
| 2687 | break; |
| 2688 | } |
| 2689 | case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] |
| 2690 | if (convertToString(Record, Idx: 0, Result&: TypeName)) |
| 2691 | return error(Message: "Invalid struct name record" ); |
| 2692 | continue; |
| 2693 | |
| 2694 | case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] |
| 2695 | if (Record.empty()) |
| 2696 | return error(Message: "Invalid named struct record" ); |
| 2697 | |
| 2698 | if (NumRecords >= TypeList.size()) |
| 2699 | return error(Message: "Invalid TYPE table" ); |
| 2700 | |
| 2701 | // Check to see if this was forward referenced, if so fill in the temp. |
| 2702 | StructType *Res = cast_or_null<StructType>(Val: TypeList[NumRecords]); |
| 2703 | if (Res) { |
| 2704 | Res->setName(TypeName); |
| 2705 | TypeList[NumRecords] = nullptr; |
| 2706 | } else // Otherwise, create a new struct. |
| 2707 | Res = createIdentifiedStructType(Context, Name: TypeName); |
| 2708 | TypeName.clear(); |
| 2709 | |
| 2710 | SmallVector<Type*, 8> EltTys; |
| 2711 | for (unsigned i = 1, e = Record.size(); i != e; ++i) { |
| 2712 | if (Type *T = getTypeByID(ID: Record[i])) |
| 2713 | EltTys.push_back(Elt: T); |
| 2714 | else |
| 2715 | break; |
| 2716 | } |
| 2717 | if (EltTys.size() != Record.size()-1) |
| 2718 | return error(Message: "Invalid named struct record" ); |
| 2719 | if (auto E = Res->setBodyOrError(Elements: EltTys, isPacked: Record[0])) |
| 2720 | return E; |
| 2721 | ContainedIDs.append(in_start: Record.begin() + 1, in_end: Record.end()); |
| 2722 | ResultTy = Res; |
| 2723 | break; |
| 2724 | } |
| 2725 | case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] |
| 2726 | if (Record.size() != 1) |
| 2727 | return error(Message: "Invalid opaque type record" ); |
| 2728 | |
| 2729 | if (NumRecords >= TypeList.size()) |
| 2730 | return error(Message: "Invalid TYPE table" ); |
| 2731 | |
| 2732 | // Check to see if this was forward referenced, if so fill in the temp. |
| 2733 | StructType *Res = cast_or_null<StructType>(Val: TypeList[NumRecords]); |
| 2734 | if (Res) { |
| 2735 | Res->setName(TypeName); |
| 2736 | TypeList[NumRecords] = nullptr; |
| 2737 | } else // Otherwise, create a new struct with no body. |
| 2738 | Res = createIdentifiedStructType(Context, Name: TypeName); |
| 2739 | TypeName.clear(); |
| 2740 | ResultTy = Res; |
| 2741 | break; |
| 2742 | } |
| 2743 | case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...] |
| 2744 | if (Record.size() < 1) |
| 2745 | return error(Message: "Invalid target extension type record" ); |
| 2746 | |
| 2747 | if (NumRecords >= TypeList.size()) |
| 2748 | return error(Message: "Invalid TYPE table" ); |
| 2749 | |
| 2750 | if (Record[0] >= Record.size()) |
| 2751 | return error(Message: "Too many type parameters" ); |
| 2752 | |
| 2753 | unsigned NumTys = Record[0]; |
| 2754 | SmallVector<Type *, 4> TypeParams; |
| 2755 | SmallVector<unsigned, 8> IntParams; |
| 2756 | for (unsigned i = 0; i < NumTys; i++) { |
| 2757 | if (Type *T = getTypeByID(ID: Record[i + 1])) |
| 2758 | TypeParams.push_back(Elt: T); |
| 2759 | else |
| 2760 | return error(Message: "Invalid type" ); |
| 2761 | } |
| 2762 | |
| 2763 | for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) { |
| 2764 | if (Record[i] > UINT_MAX) |
| 2765 | return error(Message: "Integer parameter too large" ); |
| 2766 | IntParams.push_back(Elt: Record[i]); |
| 2767 | } |
| 2768 | auto TTy = |
| 2769 | TargetExtType::getOrError(Context, Name: TypeName, Types: TypeParams, Ints: IntParams); |
| 2770 | if (auto E = TTy.takeError()) |
| 2771 | return E; |
| 2772 | ResultTy = *TTy; |
| 2773 | TypeName.clear(); |
| 2774 | break; |
| 2775 | } |
| 2776 | case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] |
| 2777 | if (Record.size() < 2) |
| 2778 | return error(Message: "Invalid array type record" ); |
| 2779 | ResultTy = getTypeByID(ID: Record[1]); |
| 2780 | if (!ResultTy || !ArrayType::isValidElementType(ElemTy: ResultTy)) |
| 2781 | return error(Message: "Invalid type" ); |
| 2782 | ContainedIDs.push_back(Elt: Record[1]); |
| 2783 | ResultTy = ArrayType::get(ElementType: ResultTy, NumElements: Record[0]); |
| 2784 | break; |
| 2785 | case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or |
| 2786 | // [numelts, eltty, scalable] |
| 2787 | if (Record.size() < 2) |
| 2788 | return error(Message: "Invalid vector type record" ); |
| 2789 | if (Record[0] == 0) |
| 2790 | return error(Message: "Invalid vector length" ); |
| 2791 | ResultTy = getTypeByID(ID: Record[1]); |
| 2792 | if (!ResultTy || !VectorType::isValidElementType(ElemTy: ResultTy)) |
| 2793 | return error(Message: "Invalid type" ); |
| 2794 | bool Scalable = Record.size() > 2 ? Record[2] : false; |
| 2795 | ContainedIDs.push_back(Elt: Record[1]); |
| 2796 | ResultTy = VectorType::get(ElementType: ResultTy, NumElements: Record[0], Scalable); |
| 2797 | break; |
| 2798 | } |
| 2799 | |
| 2800 | if (NumRecords >= TypeList.size()) |
| 2801 | return error(Message: "Invalid TYPE table" ); |
| 2802 | if (TypeList[NumRecords]) |
| 2803 | return error( |
| 2804 | Message: "Invalid TYPE table: Only named structs can be forward referenced" ); |
| 2805 | assert(ResultTy && "Didn't read a type?" ); |
| 2806 | TypeList[NumRecords] = ResultTy; |
| 2807 | if (!ContainedIDs.empty()) |
| 2808 | ContainedTypeIDs[NumRecords] = std::move(ContainedIDs); |
| 2809 | ++NumRecords; |
| 2810 | } |
| 2811 | } |
| 2812 | |
| 2813 | Error BitcodeReader::parseOperandBundleTags() { |
| 2814 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) |
| 2815 | return Err; |
| 2816 | |
| 2817 | if (!BundleTags.empty()) |
| 2818 | return error(Message: "Invalid multiple blocks" ); |
| 2819 | |
| 2820 | SmallVector<uint64_t, 64> Record; |
| 2821 | |
| 2822 | while (true) { |
| 2823 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 2824 | if (!MaybeEntry) |
| 2825 | return MaybeEntry.takeError(); |
| 2826 | BitstreamEntry Entry = MaybeEntry.get(); |
| 2827 | |
| 2828 | switch (Entry.Kind) { |
| 2829 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 2830 | case BitstreamEntry::Error: |
| 2831 | return error(Message: "Malformed block" ); |
| 2832 | case BitstreamEntry::EndBlock: |
| 2833 | return Error::success(); |
| 2834 | case BitstreamEntry::Record: |
| 2835 | // The interesting case. |
| 2836 | break; |
| 2837 | } |
| 2838 | |
| 2839 | // Tags are implicitly mapped to integers by their order. |
| 2840 | |
| 2841 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 2842 | if (!MaybeRecord) |
| 2843 | return MaybeRecord.takeError(); |
| 2844 | if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG) |
| 2845 | return error(Message: "Invalid operand bundle record" ); |
| 2846 | |
| 2847 | // OPERAND_BUNDLE_TAG: [strchr x N] |
| 2848 | BundleTags.emplace_back(); |
| 2849 | if (convertToString(Record, Idx: 0, Result&: BundleTags.back())) |
| 2850 | return error(Message: "Invalid operand bundle record" ); |
| 2851 | Record.clear(); |
| 2852 | } |
| 2853 | } |
| 2854 | |
| 2855 | Error BitcodeReader::parseSyncScopeNames() { |
| 2856 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) |
| 2857 | return Err; |
| 2858 | |
| 2859 | if (!SSIDs.empty()) |
| 2860 | return error(Message: "Invalid multiple synchronization scope names blocks" ); |
| 2861 | |
| 2862 | SmallVector<uint64_t, 64> Record; |
| 2863 | while (true) { |
| 2864 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 2865 | if (!MaybeEntry) |
| 2866 | return MaybeEntry.takeError(); |
| 2867 | BitstreamEntry Entry = MaybeEntry.get(); |
| 2868 | |
| 2869 | switch (Entry.Kind) { |
| 2870 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 2871 | case BitstreamEntry::Error: |
| 2872 | return error(Message: "Malformed block" ); |
| 2873 | case BitstreamEntry::EndBlock: |
| 2874 | if (SSIDs.empty()) |
| 2875 | return error(Message: "Invalid empty synchronization scope names block" ); |
| 2876 | return Error::success(); |
| 2877 | case BitstreamEntry::Record: |
| 2878 | // The interesting case. |
| 2879 | break; |
| 2880 | } |
| 2881 | |
| 2882 | // Synchronization scope names are implicitly mapped to synchronization |
| 2883 | // scope IDs by their order. |
| 2884 | |
| 2885 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 2886 | if (!MaybeRecord) |
| 2887 | return MaybeRecord.takeError(); |
| 2888 | if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME) |
| 2889 | return error(Message: "Invalid sync scope record" ); |
| 2890 | |
| 2891 | SmallString<16> SSN; |
| 2892 | if (convertToString(Record, Idx: 0, Result&: SSN)) |
| 2893 | return error(Message: "Invalid sync scope record" ); |
| 2894 | |
| 2895 | SSIDs.push_back(Elt: Context.getOrInsertSyncScopeID(SSN)); |
| 2896 | Record.clear(); |
| 2897 | } |
| 2898 | } |
| 2899 | |
| 2900 | /// Associate a value with its name from the given index in the provided record. |
| 2901 | Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, |
| 2902 | unsigned NameIndex, Triple &TT) { |
| 2903 | SmallString<128> ValueName; |
| 2904 | if (convertToString(Record, Idx: NameIndex, Result&: ValueName)) |
| 2905 | return error(Message: "Invalid record" ); |
| 2906 | unsigned ValueID = Record[0]; |
| 2907 | if (ValueID >= ValueList.size() || !ValueList[ValueID]) |
| 2908 | return error(Message: "Invalid record" ); |
| 2909 | Value *V = ValueList[ValueID]; |
| 2910 | |
| 2911 | StringRef NameStr(ValueName.data(), ValueName.size()); |
| 2912 | if (NameStr.contains(C: 0)) |
| 2913 | return error(Message: "Invalid value name" ); |
| 2914 | V->setName(NameStr); |
| 2915 | auto *GO = dyn_cast<GlobalObject>(Val: V); |
| 2916 | if (GO && ImplicitComdatObjects.contains(V: GO) && TT.supportsCOMDAT()) |
| 2917 | GO->setComdat(TheModule->getOrInsertComdat(Name: V->getName())); |
| 2918 | return V; |
| 2919 | } |
| 2920 | |
| 2921 | /// Helper to note and return the current location, and jump to the given |
| 2922 | /// offset. |
| 2923 | static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset, |
| 2924 | BitstreamCursor &Stream) { |
| 2925 | // Save the current parsing location so we can jump back at the end |
| 2926 | // of the VST read. |
| 2927 | uint64_t CurrentBit = Stream.GetCurrentBitNo(); |
| 2928 | if (Error JumpFailed = Stream.JumpToBit(BitNo: Offset * 32)) |
| 2929 | return std::move(JumpFailed); |
| 2930 | Expected<BitstreamEntry> MaybeEntry = Stream.advance(); |
| 2931 | if (!MaybeEntry) |
| 2932 | return MaybeEntry.takeError(); |
| 2933 | if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock || |
| 2934 | MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID) |
| 2935 | return error(Message: "Expected value symbol table subblock" ); |
| 2936 | return CurrentBit; |
| 2937 | } |
| 2938 | |
| 2939 | void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, |
| 2940 | Function *F, |
| 2941 | ArrayRef<uint64_t> Record) { |
| 2942 | // Note that we subtract 1 here because the offset is relative to one word |
| 2943 | // before the start of the identification or module block, which was |
| 2944 | // historically always the start of the regular bitcode header. |
| 2945 | uint64_t FuncWordOffset = Record[1] - 1; |
| 2946 | uint64_t FuncBitOffset = FuncWordOffset * 32; |
| 2947 | DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; |
| 2948 | // Set the LastFunctionBlockBit to point to the last function block. |
| 2949 | // Later when parsing is resumed after function materialization, |
| 2950 | // we can simply skip that last function block. |
| 2951 | if (FuncBitOffset > LastFunctionBlockBit) |
| 2952 | LastFunctionBlockBit = FuncBitOffset; |
| 2953 | } |
| 2954 | |
| 2955 | /// Read a new-style GlobalValue symbol table. |
| 2956 | Error BitcodeReader::parseGlobalValueSymbolTable() { |
| 2957 | unsigned FuncBitcodeOffsetDelta = |
| 2958 | Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; |
| 2959 | |
| 2960 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::VALUE_SYMTAB_BLOCK_ID)) |
| 2961 | return Err; |
| 2962 | |
| 2963 | SmallVector<uint64_t, 64> Record; |
| 2964 | while (true) { |
| 2965 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 2966 | if (!MaybeEntry) |
| 2967 | return MaybeEntry.takeError(); |
| 2968 | BitstreamEntry Entry = MaybeEntry.get(); |
| 2969 | |
| 2970 | switch (Entry.Kind) { |
| 2971 | case BitstreamEntry::SubBlock: |
| 2972 | case BitstreamEntry::Error: |
| 2973 | return error(Message: "Malformed block" ); |
| 2974 | case BitstreamEntry::EndBlock: |
| 2975 | return Error::success(); |
| 2976 | case BitstreamEntry::Record: |
| 2977 | break; |
| 2978 | } |
| 2979 | |
| 2980 | Record.clear(); |
| 2981 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 2982 | if (!MaybeRecord) |
| 2983 | return MaybeRecord.takeError(); |
| 2984 | switch (MaybeRecord.get()) { |
| 2985 | case bitc::VST_CODE_FNENTRY: { // [valueid, offset] |
| 2986 | unsigned ValueID = Record[0]; |
| 2987 | if (ValueID >= ValueList.size() || !ValueList[ValueID]) |
| 2988 | return error(Message: "Invalid value reference in symbol table" ); |
| 2989 | setDeferredFunctionInfo(FuncBitcodeOffsetDelta, |
| 2990 | F: cast<Function>(Val: ValueList[ValueID]), Record); |
| 2991 | break; |
| 2992 | } |
| 2993 | } |
| 2994 | } |
| 2995 | } |
| 2996 | |
| 2997 | /// Parse the value symbol table at either the current parsing location or |
| 2998 | /// at the given bit offset if provided. |
| 2999 | Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { |
| 3000 | uint64_t CurrentBit; |
| 3001 | // Pass in the Offset to distinguish between calling for the module-level |
| 3002 | // VST (where we want to jump to the VST offset) and the function-level |
| 3003 | // VST (where we don't). |
| 3004 | if (Offset > 0) { |
| 3005 | Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); |
| 3006 | if (!MaybeCurrentBit) |
| 3007 | return MaybeCurrentBit.takeError(); |
| 3008 | CurrentBit = MaybeCurrentBit.get(); |
| 3009 | // If this module uses a string table, read this as a module-level VST. |
| 3010 | if (UseStrtab) { |
| 3011 | if (Error Err = parseGlobalValueSymbolTable()) |
| 3012 | return Err; |
| 3013 | if (Error JumpFailed = Stream.JumpToBit(BitNo: CurrentBit)) |
| 3014 | return JumpFailed; |
| 3015 | return Error::success(); |
| 3016 | } |
| 3017 | // Otherwise, the VST will be in a similar format to a function-level VST, |
| 3018 | // and will contain symbol names. |
| 3019 | } |
| 3020 | |
| 3021 | // Compute the delta between the bitcode indices in the VST (the word offset |
| 3022 | // to the word-aligned ENTER_SUBBLOCK for the function block, and that |
| 3023 | // expected by the lazy reader. The reader's EnterSubBlock expects to have |
| 3024 | // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID |
| 3025 | // (size BlockIDWidth). Note that we access the stream's AbbrevID width here |
| 3026 | // just before entering the VST subblock because: 1) the EnterSubBlock |
| 3027 | // changes the AbbrevID width; 2) the VST block is nested within the same |
| 3028 | // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same |
| 3029 | // AbbrevID width before calling EnterSubBlock; and 3) when we want to |
| 3030 | // jump to the FUNCTION_BLOCK using this offset later, we don't want |
| 3031 | // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. |
| 3032 | unsigned FuncBitcodeOffsetDelta = |
| 3033 | Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; |
| 3034 | |
| 3035 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::VALUE_SYMTAB_BLOCK_ID)) |
| 3036 | return Err; |
| 3037 | |
| 3038 | SmallVector<uint64_t, 64> Record; |
| 3039 | |
| 3040 | Triple TT(TheModule->getTargetTriple()); |
| 3041 | |
| 3042 | // Read all the records for this value table. |
| 3043 | SmallString<128> ValueName; |
| 3044 | |
| 3045 | while (true) { |
| 3046 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 3047 | if (!MaybeEntry) |
| 3048 | return MaybeEntry.takeError(); |
| 3049 | BitstreamEntry Entry = MaybeEntry.get(); |
| 3050 | |
| 3051 | switch (Entry.Kind) { |
| 3052 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 3053 | case BitstreamEntry::Error: |
| 3054 | return error(Message: "Malformed block" ); |
| 3055 | case BitstreamEntry::EndBlock: |
| 3056 | if (Offset > 0) |
| 3057 | if (Error JumpFailed = Stream.JumpToBit(BitNo: CurrentBit)) |
| 3058 | return JumpFailed; |
| 3059 | return Error::success(); |
| 3060 | case BitstreamEntry::Record: |
| 3061 | // The interesting case. |
| 3062 | break; |
| 3063 | } |
| 3064 | |
| 3065 | // Read a record. |
| 3066 | Record.clear(); |
| 3067 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 3068 | if (!MaybeRecord) |
| 3069 | return MaybeRecord.takeError(); |
| 3070 | switch (MaybeRecord.get()) { |
| 3071 | default: // Default behavior: unknown type. |
| 3072 | break; |
| 3073 | case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] |
| 3074 | Expected<Value *> ValOrErr = recordValue(Record, NameIndex: 1, TT); |
| 3075 | if (Error Err = ValOrErr.takeError()) |
| 3076 | return Err; |
| 3077 | ValOrErr.get(); |
| 3078 | break; |
| 3079 | } |
| 3080 | case bitc::VST_CODE_FNENTRY: { |
| 3081 | // VST_CODE_FNENTRY: [valueid, offset, namechar x N] |
| 3082 | Expected<Value *> ValOrErr = recordValue(Record, NameIndex: 2, TT); |
| 3083 | if (Error Err = ValOrErr.takeError()) |
| 3084 | return Err; |
| 3085 | Value *V = ValOrErr.get(); |
| 3086 | |
| 3087 | // Ignore function offsets emitted for aliases of functions in older |
| 3088 | // versions of LLVM. |
| 3089 | if (auto *F = dyn_cast<Function>(Val: V)) |
| 3090 | setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); |
| 3091 | break; |
| 3092 | } |
| 3093 | case bitc::VST_CODE_BBENTRY: { |
| 3094 | if (convertToString(Record, Idx: 1, Result&: ValueName)) |
| 3095 | return error(Message: "Invalid bbentry record" ); |
| 3096 | BasicBlock *BB = getBasicBlock(ID: Record[0]); |
| 3097 | if (!BB) |
| 3098 | return error(Message: "Invalid bbentry record" ); |
| 3099 | |
| 3100 | BB->setName(ValueName.str()); |
| 3101 | ValueName.clear(); |
| 3102 | break; |
| 3103 | } |
| 3104 | } |
| 3105 | } |
| 3106 | } |
| 3107 | |
| 3108 | /// Decode a signed value stored with the sign bit in the LSB for dense VBR |
| 3109 | /// encoding. |
| 3110 | uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { |
| 3111 | if ((V & 1) == 0) |
| 3112 | return V >> 1; |
| 3113 | if (V != 1) |
| 3114 | return -(V >> 1); |
| 3115 | // There is no such thing as -0 with integers. "-0" really means MININT. |
| 3116 | return 1ULL << 63; |
| 3117 | } |
| 3118 | |
| 3119 | /// Resolve all of the initializers for global values and aliases that we can. |
| 3120 | Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { |
| 3121 | std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; |
| 3122 | std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist; |
| 3123 | std::vector<FunctionOperandInfo> FunctionOperandWorklist; |
| 3124 | |
| 3125 | GlobalInitWorklist.swap(x&: GlobalInits); |
| 3126 | IndirectSymbolInitWorklist.swap(x&: IndirectSymbolInits); |
| 3127 | FunctionOperandWorklist.swap(x&: FunctionOperands); |
| 3128 | |
| 3129 | while (!GlobalInitWorklist.empty()) { |
| 3130 | unsigned ValID = GlobalInitWorklist.back().second; |
| 3131 | if (ValID >= ValueList.size()) { |
| 3132 | // Not ready to resolve this yet, it requires something later in the file. |
| 3133 | GlobalInits.push_back(x: GlobalInitWorklist.back()); |
| 3134 | } else { |
| 3135 | Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID); |
| 3136 | if (!MaybeC) |
| 3137 | return MaybeC.takeError(); |
| 3138 | GlobalInitWorklist.back().first->setInitializer(MaybeC.get()); |
| 3139 | } |
| 3140 | GlobalInitWorklist.pop_back(); |
| 3141 | } |
| 3142 | |
| 3143 | while (!IndirectSymbolInitWorklist.empty()) { |
| 3144 | unsigned ValID = IndirectSymbolInitWorklist.back().second; |
| 3145 | if (ValID >= ValueList.size()) { |
| 3146 | IndirectSymbolInits.push_back(x: IndirectSymbolInitWorklist.back()); |
| 3147 | } else { |
| 3148 | Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID); |
| 3149 | if (!MaybeC) |
| 3150 | return MaybeC.takeError(); |
| 3151 | Constant *C = MaybeC.get(); |
| 3152 | GlobalValue *GV = IndirectSymbolInitWorklist.back().first; |
| 3153 | if (auto *GA = dyn_cast<GlobalAlias>(Val: GV)) { |
| 3154 | if (C->getType() != GV->getType()) |
| 3155 | return error(Message: "Alias and aliasee types don't match" ); |
| 3156 | GA->setAliasee(C); |
| 3157 | } else if (auto *GI = dyn_cast<GlobalIFunc>(Val: GV)) { |
| 3158 | GI->setResolver(C); |
| 3159 | } else { |
| 3160 | return error(Message: "Expected an alias or an ifunc" ); |
| 3161 | } |
| 3162 | } |
| 3163 | IndirectSymbolInitWorklist.pop_back(); |
| 3164 | } |
| 3165 | |
| 3166 | while (!FunctionOperandWorklist.empty()) { |
| 3167 | FunctionOperandInfo &Info = FunctionOperandWorklist.back(); |
| 3168 | if (Info.PersonalityFn) { |
| 3169 | unsigned ValID = Info.PersonalityFn - 1; |
| 3170 | if (ValID < ValueList.size()) { |
| 3171 | Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID); |
| 3172 | if (!MaybeC) |
| 3173 | return MaybeC.takeError(); |
| 3174 | Info.F->setPersonalityFn(MaybeC.get()); |
| 3175 | Info.PersonalityFn = 0; |
| 3176 | } |
| 3177 | } |
| 3178 | if (Info.Prefix) { |
| 3179 | unsigned ValID = Info.Prefix - 1; |
| 3180 | if (ValID < ValueList.size()) { |
| 3181 | Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID); |
| 3182 | if (!MaybeC) |
| 3183 | return MaybeC.takeError(); |
| 3184 | Info.F->setPrefixData(MaybeC.get()); |
| 3185 | Info.Prefix = 0; |
| 3186 | } |
| 3187 | } |
| 3188 | if (Info.Prologue) { |
| 3189 | unsigned ValID = Info.Prologue - 1; |
| 3190 | if (ValID < ValueList.size()) { |
| 3191 | Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID); |
| 3192 | if (!MaybeC) |
| 3193 | return MaybeC.takeError(); |
| 3194 | Info.F->setPrologueData(MaybeC.get()); |
| 3195 | Info.Prologue = 0; |
| 3196 | } |
| 3197 | } |
| 3198 | if (Info.PersonalityFn || Info.Prefix || Info.Prologue) |
| 3199 | FunctionOperands.push_back(x: Info); |
| 3200 | FunctionOperandWorklist.pop_back(); |
| 3201 | } |
| 3202 | |
| 3203 | return Error::success(); |
| 3204 | } |
| 3205 | |
| 3206 | APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { |
| 3207 | SmallVector<uint64_t, 8> Words(Vals.size()); |
| 3208 | transform(Range&: Vals, d_first: Words.begin(), |
| 3209 | F: BitcodeReader::decodeSignRotatedValue); |
| 3210 | |
| 3211 | return APInt(TypeBits, Words); |
| 3212 | } |
| 3213 | |
| 3214 | Error BitcodeReader::parseConstants() { |
| 3215 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::CONSTANTS_BLOCK_ID)) |
| 3216 | return Err; |
| 3217 | |
| 3218 | SmallVector<uint64_t, 64> Record; |
| 3219 | |
| 3220 | // Read all the records for this value table. |
| 3221 | Type *CurTy = Type::getInt32Ty(C&: Context); |
| 3222 | unsigned Int32TyID = getVirtualTypeID(Ty: CurTy); |
| 3223 | unsigned CurTyID = Int32TyID; |
| 3224 | Type *CurElemTy = nullptr; |
| 3225 | unsigned NextCstNo = ValueList.size(); |
| 3226 | |
| 3227 | while (true) { |
| 3228 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 3229 | if (!MaybeEntry) |
| 3230 | return MaybeEntry.takeError(); |
| 3231 | BitstreamEntry Entry = MaybeEntry.get(); |
| 3232 | |
| 3233 | switch (Entry.Kind) { |
| 3234 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 3235 | case BitstreamEntry::Error: |
| 3236 | return error(Message: "Malformed block" ); |
| 3237 | case BitstreamEntry::EndBlock: |
| 3238 | if (NextCstNo != ValueList.size()) |
| 3239 | return error(Message: "Invalid constant reference" ); |
| 3240 | return Error::success(); |
| 3241 | case BitstreamEntry::Record: |
| 3242 | // The interesting case. |
| 3243 | break; |
| 3244 | } |
| 3245 | |
| 3246 | // Read a record. |
| 3247 | Record.clear(); |
| 3248 | Type *VoidType = Type::getVoidTy(C&: Context); |
| 3249 | Value *V = nullptr; |
| 3250 | Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 3251 | if (!MaybeBitCode) |
| 3252 | return MaybeBitCode.takeError(); |
| 3253 | switch (unsigned BitCode = MaybeBitCode.get()) { |
| 3254 | default: // Default behavior: unknown constant |
| 3255 | case bitc::CST_CODE_UNDEF: // UNDEF |
| 3256 | V = UndefValue::get(T: CurTy); |
| 3257 | break; |
| 3258 | case bitc::CST_CODE_POISON: // POISON |
| 3259 | V = PoisonValue::get(T: CurTy); |
| 3260 | break; |
| 3261 | case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] |
| 3262 | if (Record.empty()) |
| 3263 | return error(Message: "Invalid settype record" ); |
| 3264 | if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) |
| 3265 | return error(Message: "Invalid settype record" ); |
| 3266 | if (TypeList[Record[0]] == VoidType) |
| 3267 | return error(Message: "Invalid constant type" ); |
| 3268 | CurTyID = Record[0]; |
| 3269 | CurTy = TypeList[CurTyID]; |
| 3270 | CurElemTy = getPtrElementTypeByID(ID: CurTyID); |
| 3271 | continue; // Skip the ValueList manipulation. |
| 3272 | case bitc::CST_CODE_NULL: // NULL |
| 3273 | if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy()) |
| 3274 | return error(Message: "Invalid type for a constant null value" ); |
| 3275 | if (auto *TETy = dyn_cast<TargetExtType>(Val: CurTy)) |
| 3276 | if (!TETy->hasProperty(Prop: TargetExtType::HasZeroInit)) |
| 3277 | return error(Message: "Invalid type for a constant null value" ); |
| 3278 | V = Constant::getNullValue(Ty: CurTy); |
| 3279 | break; |
| 3280 | case bitc::CST_CODE_INTEGER: // INTEGER: [intval] |
| 3281 | if (!CurTy->isIntOrIntVectorTy() || Record.empty()) |
| 3282 | return error(Message: "Invalid integer const record" ); |
| 3283 | V = ConstantInt::get(Ty: CurTy, V: decodeSignRotatedValue(V: Record[0])); |
| 3284 | break; |
| 3285 | case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] |
| 3286 | if (!CurTy->isIntOrIntVectorTy() || Record.empty()) |
| 3287 | return error(Message: "Invalid wide integer const record" ); |
| 3288 | |
| 3289 | auto *ScalarTy = cast<IntegerType>(Val: CurTy->getScalarType()); |
| 3290 | APInt VInt = readWideAPInt(Vals: Record, TypeBits: ScalarTy->getBitWidth()); |
| 3291 | V = ConstantInt::get(Ty: CurTy, V: VInt); |
| 3292 | break; |
| 3293 | } |
| 3294 | case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] |
| 3295 | if (Record.empty()) |
| 3296 | return error(Message: "Invalid float const record" ); |
| 3297 | |
| 3298 | auto *ScalarTy = CurTy->getScalarType(); |
| 3299 | if (ScalarTy->isHalfTy()) |
| 3300 | V = ConstantFP::get(Ty: CurTy, V: APFloat(APFloat::IEEEhalf(), |
| 3301 | APInt(16, (uint16_t)Record[0]))); |
| 3302 | else if (ScalarTy->isBFloatTy()) |
| 3303 | V = ConstantFP::get( |
| 3304 | Ty: CurTy, V: APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0]))); |
| 3305 | else if (ScalarTy->isFloatTy()) |
| 3306 | V = ConstantFP::get(Ty: CurTy, V: APFloat(APFloat::IEEEsingle(), |
| 3307 | APInt(32, (uint32_t)Record[0]))); |
| 3308 | else if (ScalarTy->isDoubleTy()) |
| 3309 | V = ConstantFP::get( |
| 3310 | Ty: CurTy, V: APFloat(APFloat::IEEEdouble(), APInt(64, Record[0]))); |
| 3311 | else if (ScalarTy->isX86_FP80Ty()) { |
| 3312 | // Bits are not stored the same way as a normal i80 APInt, compensate. |
| 3313 | uint64_t Rearrange[2]; |
| 3314 | Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); |
| 3315 | Rearrange[1] = Record[0] >> 48; |
| 3316 | V = ConstantFP::get( |
| 3317 | Ty: CurTy, V: APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange))); |
| 3318 | } else if (ScalarTy->isFP128Ty()) |
| 3319 | V = ConstantFP::get(Ty: CurTy, |
| 3320 | V: APFloat(APFloat::IEEEquad(), APInt(128, Record))); |
| 3321 | else if (ScalarTy->isPPC_FP128Ty()) |
| 3322 | V = ConstantFP::get( |
| 3323 | Ty: CurTy, V: APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record))); |
| 3324 | else |
| 3325 | V = PoisonValue::get(T: CurTy); |
| 3326 | break; |
| 3327 | } |
| 3328 | |
| 3329 | case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] |
| 3330 | if (Record.empty()) |
| 3331 | return error(Message: "Invalid aggregate record" ); |
| 3332 | |
| 3333 | SmallVector<unsigned, 16> Elts; |
| 3334 | llvm::append_range(C&: Elts, R&: Record); |
| 3335 | |
| 3336 | if (isa<StructType>(Val: CurTy)) { |
| 3337 | V = BitcodeConstant::create( |
| 3338 | A&: Alloc, Ty: CurTy, Info: BitcodeConstant::ConstantStructOpcode, OpIDs: Elts); |
| 3339 | } else if (isa<ArrayType>(Val: CurTy)) { |
| 3340 | V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, |
| 3341 | Info: BitcodeConstant::ConstantArrayOpcode, OpIDs: Elts); |
| 3342 | } else if (isa<VectorType>(Val: CurTy)) { |
| 3343 | V = BitcodeConstant::create( |
| 3344 | A&: Alloc, Ty: CurTy, Info: BitcodeConstant::ConstantVectorOpcode, OpIDs: Elts); |
| 3345 | } else { |
| 3346 | V = PoisonValue::get(T: CurTy); |
| 3347 | } |
| 3348 | break; |
| 3349 | } |
| 3350 | case bitc::CST_CODE_STRING: // STRING: [values] |
| 3351 | case bitc::CST_CODE_CSTRING: { // CSTRING: [values] |
| 3352 | if (Record.empty()) |
| 3353 | return error(Message: "Invalid string record" ); |
| 3354 | |
| 3355 | SmallString<16> Elts(Record.begin(), Record.end()); |
| 3356 | V = ConstantDataArray::getString(Context, Initializer: Elts, |
| 3357 | AddNull: BitCode == bitc::CST_CODE_CSTRING); |
| 3358 | break; |
| 3359 | } |
| 3360 | case bitc::CST_CODE_DATA: {// DATA: [n x value] |
| 3361 | if (Record.empty()) |
| 3362 | return error(Message: "Invalid data record" ); |
| 3363 | |
| 3364 | Type *EltTy; |
| 3365 | if (auto *Array = dyn_cast<ArrayType>(Val: CurTy)) |
| 3366 | EltTy = Array->getElementType(); |
| 3367 | else |
| 3368 | EltTy = cast<VectorType>(Val: CurTy)->getElementType(); |
| 3369 | if (EltTy->isIntegerTy(Bitwidth: 8)) { |
| 3370 | SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); |
| 3371 | if (isa<VectorType>(Val: CurTy)) |
| 3372 | V = ConstantDataVector::get(Context, Elts); |
| 3373 | else |
| 3374 | V = ConstantDataArray::get(Context, Elts); |
| 3375 | } else if (EltTy->isIntegerTy(Bitwidth: 16)) { |
| 3376 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); |
| 3377 | if (isa<VectorType>(Val: CurTy)) |
| 3378 | V = ConstantDataVector::get(Context, Elts); |
| 3379 | else |
| 3380 | V = ConstantDataArray::get(Context, Elts); |
| 3381 | } else if (EltTy->isIntegerTy(Bitwidth: 32)) { |
| 3382 | SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); |
| 3383 | if (isa<VectorType>(Val: CurTy)) |
| 3384 | V = ConstantDataVector::get(Context, Elts); |
| 3385 | else |
| 3386 | V = ConstantDataArray::get(Context, Elts); |
| 3387 | } else if (EltTy->isIntegerTy(Bitwidth: 64)) { |
| 3388 | SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); |
| 3389 | if (isa<VectorType>(Val: CurTy)) |
| 3390 | V = ConstantDataVector::get(Context, Elts); |
| 3391 | else |
| 3392 | V = ConstantDataArray::get(Context, Elts); |
| 3393 | } else if (EltTy->isHalfTy()) { |
| 3394 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); |
| 3395 | if (isa<VectorType>(Val: CurTy)) |
| 3396 | V = ConstantDataVector::getFP(ElementType: EltTy, Elts); |
| 3397 | else |
| 3398 | V = ConstantDataArray::getFP(ElementType: EltTy, Elts); |
| 3399 | } else if (EltTy->isBFloatTy()) { |
| 3400 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); |
| 3401 | if (isa<VectorType>(Val: CurTy)) |
| 3402 | V = ConstantDataVector::getFP(ElementType: EltTy, Elts); |
| 3403 | else |
| 3404 | V = ConstantDataArray::getFP(ElementType: EltTy, Elts); |
| 3405 | } else if (EltTy->isFloatTy()) { |
| 3406 | SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); |
| 3407 | if (isa<VectorType>(Val: CurTy)) |
| 3408 | V = ConstantDataVector::getFP(ElementType: EltTy, Elts); |
| 3409 | else |
| 3410 | V = ConstantDataArray::getFP(ElementType: EltTy, Elts); |
| 3411 | } else if (EltTy->isDoubleTy()) { |
| 3412 | SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); |
| 3413 | if (isa<VectorType>(Val: CurTy)) |
| 3414 | V = ConstantDataVector::getFP(ElementType: EltTy, Elts); |
| 3415 | else |
| 3416 | V = ConstantDataArray::getFP(ElementType: EltTy, Elts); |
| 3417 | } else { |
| 3418 | return error(Message: "Invalid type for value" ); |
| 3419 | } |
| 3420 | break; |
| 3421 | } |
| 3422 | case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] |
| 3423 | if (Record.size() < 2) |
| 3424 | return error(Message: "Invalid unary op constexpr record" ); |
| 3425 | int Opc = getDecodedUnaryOpcode(Val: Record[0], Ty: CurTy); |
| 3426 | if (Opc < 0) { |
| 3427 | V = PoisonValue::get(T: CurTy); // Unknown unop. |
| 3428 | } else { |
| 3429 | V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: Opc, OpIDs: (unsigned)Record[1]); |
| 3430 | } |
| 3431 | break; |
| 3432 | } |
| 3433 | case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] |
| 3434 | if (Record.size() < 3) |
| 3435 | return error(Message: "Invalid binary op constexpr record" ); |
| 3436 | int Opc = getDecodedBinaryOpcode(Val: Record[0], Ty: CurTy); |
| 3437 | if (Opc < 0) { |
| 3438 | V = PoisonValue::get(T: CurTy); // Unknown binop. |
| 3439 | } else { |
| 3440 | uint8_t Flags = 0; |
| 3441 | if (Record.size() >= 4) { |
| 3442 | if (Opc == Instruction::Add || |
| 3443 | Opc == Instruction::Sub || |
| 3444 | Opc == Instruction::Mul || |
| 3445 | Opc == Instruction::Shl) { |
| 3446 | if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) |
| 3447 | Flags |= OverflowingBinaryOperator::NoSignedWrap; |
| 3448 | if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) |
| 3449 | Flags |= OverflowingBinaryOperator::NoUnsignedWrap; |
| 3450 | } else if (Opc == Instruction::SDiv || |
| 3451 | Opc == Instruction::UDiv || |
| 3452 | Opc == Instruction::LShr || |
| 3453 | Opc == Instruction::AShr) { |
| 3454 | if (Record[3] & (1 << bitc::PEO_EXACT)) |
| 3455 | Flags |= PossiblyExactOperator::IsExact; |
| 3456 | } |
| 3457 | } |
| 3458 | V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: {(uint8_t)Opc, Flags}, |
| 3459 | OpIDs: {(unsigned)Record[1], (unsigned)Record[2]}); |
| 3460 | } |
| 3461 | break; |
| 3462 | } |
| 3463 | case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] |
| 3464 | if (Record.size() < 3) |
| 3465 | return error(Message: "Invalid cast constexpr record" ); |
| 3466 | int Opc = getDecodedCastOpcode(Val: Record[0]); |
| 3467 | if (Opc < 0) { |
| 3468 | V = PoisonValue::get(T: CurTy); // Unknown cast. |
| 3469 | } else { |
| 3470 | unsigned OpTyID = Record[1]; |
| 3471 | Type *OpTy = getTypeByID(ID: OpTyID); |
| 3472 | if (!OpTy) |
| 3473 | return error(Message: "Invalid cast constexpr record" ); |
| 3474 | V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: Opc, OpIDs: (unsigned)Record[2]); |
| 3475 | } |
| 3476 | break; |
| 3477 | } |
| 3478 | case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] |
| 3479 | case bitc::CST_CODE_CE_GEP_OLD: // [ty, n x operands] |
| 3480 | case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD: // [ty, flags, n x |
| 3481 | // operands] |
| 3482 | case bitc::CST_CODE_CE_GEP: // [ty, flags, n x operands] |
| 3483 | case bitc::CST_CODE_CE_GEP_WITH_INRANGE: { // [ty, flags, start, end, n x |
| 3484 | // operands] |
| 3485 | if (Record.size() < 2) |
| 3486 | return error(Message: "Constant GEP record must have at least two elements" ); |
| 3487 | unsigned OpNum = 0; |
| 3488 | Type *PointeeType = nullptr; |
| 3489 | if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD || |
| 3490 | BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE || |
| 3491 | BitCode == bitc::CST_CODE_CE_GEP || Record.size() % 2) |
| 3492 | PointeeType = getTypeByID(ID: Record[OpNum++]); |
| 3493 | |
| 3494 | uint64_t Flags = 0; |
| 3495 | std::optional<ConstantRange> InRange; |
| 3496 | if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD) { |
| 3497 | uint64_t Op = Record[OpNum++]; |
| 3498 | Flags = Op & 1; // inbounds |
| 3499 | unsigned InRangeIndex = Op >> 1; |
| 3500 | // "Upgrade" inrange by dropping it. The feature is too niche to |
| 3501 | // bother. |
| 3502 | (void)InRangeIndex; |
| 3503 | } else if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE) { |
| 3504 | Flags = Record[OpNum++]; |
| 3505 | Expected<ConstantRange> MaybeInRange = |
| 3506 | readBitWidthAndConstantRange(Record, OpNum); |
| 3507 | if (!MaybeInRange) |
| 3508 | return MaybeInRange.takeError(); |
| 3509 | InRange = MaybeInRange.get(); |
| 3510 | } else if (BitCode == bitc::CST_CODE_CE_GEP) { |
| 3511 | Flags = Record[OpNum++]; |
| 3512 | } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) |
| 3513 | Flags = (1 << bitc::GEP_INBOUNDS); |
| 3514 | |
| 3515 | SmallVector<unsigned, 16> Elts; |
| 3516 | unsigned BaseTypeID = Record[OpNum]; |
| 3517 | while (OpNum != Record.size()) { |
| 3518 | unsigned ElTyID = Record[OpNum++]; |
| 3519 | Type *ElTy = getTypeByID(ID: ElTyID); |
| 3520 | if (!ElTy) |
| 3521 | return error(Message: "Invalid getelementptr constexpr record" ); |
| 3522 | Elts.push_back(Elt: Record[OpNum++]); |
| 3523 | } |
| 3524 | |
| 3525 | if (Elts.size() < 1) |
| 3526 | return error(Message: "Invalid gep with no operands" ); |
| 3527 | |
| 3528 | Type *BaseType = getTypeByID(ID: BaseTypeID); |
| 3529 | if (isa<VectorType>(Val: BaseType)) { |
| 3530 | BaseTypeID = getContainedTypeID(ID: BaseTypeID, Idx: 0); |
| 3531 | BaseType = getTypeByID(ID: BaseTypeID); |
| 3532 | } |
| 3533 | |
| 3534 | PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(Val: BaseType); |
| 3535 | if (!OrigPtrTy) |
| 3536 | return error(Message: "GEP base operand must be pointer or vector of pointer" ); |
| 3537 | |
| 3538 | if (!PointeeType) { |
| 3539 | PointeeType = getPtrElementTypeByID(ID: BaseTypeID); |
| 3540 | if (!PointeeType) |
| 3541 | return error(Message: "Missing element type for old-style constant GEP" ); |
| 3542 | } |
| 3543 | |
| 3544 | V = BitcodeConstant::create( |
| 3545 | A&: Alloc, Ty: CurTy, |
| 3546 | Info: {Instruction::GetElementPtr, uint8_t(Flags), PointeeType, InRange}, |
| 3547 | OpIDs: Elts); |
| 3548 | break; |
| 3549 | } |
| 3550 | case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] |
| 3551 | if (Record.size() < 3) |
| 3552 | return error(Message: "Invalid select constexpr record" ); |
| 3553 | |
| 3554 | V = BitcodeConstant::create( |
| 3555 | A&: Alloc, Ty: CurTy, Info: Instruction::Select, |
| 3556 | OpIDs: {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); |
| 3557 | break; |
| 3558 | } |
| 3559 | case bitc::CST_CODE_CE_EXTRACTELT |
| 3560 | : { // CE_EXTRACTELT: [opty, opval, opty, opval] |
| 3561 | if (Record.size() < 3) |
| 3562 | return error(Message: "Invalid extractelement constexpr record" ); |
| 3563 | unsigned OpTyID = Record[0]; |
| 3564 | VectorType *OpTy = |
| 3565 | dyn_cast_or_null<VectorType>(Val: getTypeByID(ID: OpTyID)); |
| 3566 | if (!OpTy) |
| 3567 | return error(Message: "Invalid extractelement constexpr record" ); |
| 3568 | unsigned IdxRecord; |
| 3569 | if (Record.size() == 4) { |
| 3570 | unsigned IdxTyID = Record[2]; |
| 3571 | Type *IdxTy = getTypeByID(ID: IdxTyID); |
| 3572 | if (!IdxTy) |
| 3573 | return error(Message: "Invalid extractelement constexpr record" ); |
| 3574 | IdxRecord = Record[3]; |
| 3575 | } else { |
| 3576 | // Deprecated, but still needed to read old bitcode files. |
| 3577 | IdxRecord = Record[2]; |
| 3578 | } |
| 3579 | V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: Instruction::ExtractElement, |
| 3580 | OpIDs: {(unsigned)Record[1], IdxRecord}); |
| 3581 | break; |
| 3582 | } |
| 3583 | case bitc::CST_CODE_CE_INSERTELT |
| 3584 | : { // CE_INSERTELT: [opval, opval, opty, opval] |
| 3585 | VectorType *OpTy = dyn_cast<VectorType>(Val: CurTy); |
| 3586 | if (Record.size() < 3 || !OpTy) |
| 3587 | return error(Message: "Invalid insertelement constexpr record" ); |
| 3588 | unsigned IdxRecord; |
| 3589 | if (Record.size() == 4) { |
| 3590 | unsigned IdxTyID = Record[2]; |
| 3591 | Type *IdxTy = getTypeByID(ID: IdxTyID); |
| 3592 | if (!IdxTy) |
| 3593 | return error(Message: "Invalid insertelement constexpr record" ); |
| 3594 | IdxRecord = Record[3]; |
| 3595 | } else { |
| 3596 | // Deprecated, but still needed to read old bitcode files. |
| 3597 | IdxRecord = Record[2]; |
| 3598 | } |
| 3599 | V = BitcodeConstant::create( |
| 3600 | A&: Alloc, Ty: CurTy, Info: Instruction::InsertElement, |
| 3601 | OpIDs: {(unsigned)Record[0], (unsigned)Record[1], IdxRecord}); |
| 3602 | break; |
| 3603 | } |
| 3604 | case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] |
| 3605 | VectorType *OpTy = dyn_cast<VectorType>(Val: CurTy); |
| 3606 | if (Record.size() < 3 || !OpTy) |
| 3607 | return error(Message: "Invalid shufflevector constexpr record" ); |
| 3608 | V = BitcodeConstant::create( |
| 3609 | A&: Alloc, Ty: CurTy, Info: Instruction::ShuffleVector, |
| 3610 | OpIDs: {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); |
| 3611 | break; |
| 3612 | } |
| 3613 | case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] |
| 3614 | VectorType *RTy = dyn_cast<VectorType>(Val: CurTy); |
| 3615 | VectorType *OpTy = |
| 3616 | dyn_cast_or_null<VectorType>(Val: getTypeByID(ID: Record[0])); |
| 3617 | if (Record.size() < 4 || !RTy || !OpTy) |
| 3618 | return error(Message: "Invalid shufflevector constexpr record" ); |
| 3619 | V = BitcodeConstant::create( |
| 3620 | A&: Alloc, Ty: CurTy, Info: Instruction::ShuffleVector, |
| 3621 | OpIDs: {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]}); |
| 3622 | break; |
| 3623 | } |
| 3624 | case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] |
| 3625 | if (Record.size() < 4) |
| 3626 | return error(Message: "Invalid cmp constexpt record" ); |
| 3627 | unsigned OpTyID = Record[0]; |
| 3628 | Type *OpTy = getTypeByID(ID: OpTyID); |
| 3629 | if (!OpTy) |
| 3630 | return error(Message: "Invalid cmp constexpr record" ); |
| 3631 | V = BitcodeConstant::create( |
| 3632 | A&: Alloc, Ty: CurTy, |
| 3633 | Info: {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp |
| 3634 | : Instruction::ICmp), |
| 3635 | (uint8_t)Record[3]}, |
| 3636 | OpIDs: {(unsigned)Record[1], (unsigned)Record[2]}); |
| 3637 | break; |
| 3638 | } |
| 3639 | // This maintains backward compatibility, pre-asm dialect keywords. |
| 3640 | // Deprecated, but still needed to read old bitcode files. |
| 3641 | case bitc::CST_CODE_INLINEASM_OLD: { |
| 3642 | if (Record.size() < 2) |
| 3643 | return error(Message: "Invalid inlineasm record" ); |
| 3644 | std::string AsmStr, ConstrStr; |
| 3645 | bool HasSideEffects = Record[0] & 1; |
| 3646 | bool IsAlignStack = Record[0] >> 1; |
| 3647 | unsigned AsmStrSize = Record[1]; |
| 3648 | if (2+AsmStrSize >= Record.size()) |
| 3649 | return error(Message: "Invalid inlineasm record" ); |
| 3650 | unsigned ConstStrSize = Record[2+AsmStrSize]; |
| 3651 | if (3+AsmStrSize+ConstStrSize > Record.size()) |
| 3652 | return error(Message: "Invalid inlineasm record" ); |
| 3653 | |
| 3654 | for (unsigned i = 0; i != AsmStrSize; ++i) |
| 3655 | AsmStr += (char)Record[2+i]; |
| 3656 | for (unsigned i = 0; i != ConstStrSize; ++i) |
| 3657 | ConstrStr += (char)Record[3+AsmStrSize+i]; |
| 3658 | UpgradeInlineAsmString(AsmStr: &AsmStr); |
| 3659 | if (!CurElemTy) |
| 3660 | return error(Message: "Missing element type for old-style inlineasm" ); |
| 3661 | V = InlineAsm::get(Ty: cast<FunctionType>(Val: CurElemTy), AsmString: AsmStr, Constraints: ConstrStr, |
| 3662 | hasSideEffects: HasSideEffects, isAlignStack: IsAlignStack); |
| 3663 | break; |
| 3664 | } |
| 3665 | // This version adds support for the asm dialect keywords (e.g., |
| 3666 | // inteldialect). |
| 3667 | case bitc::CST_CODE_INLINEASM_OLD2: { |
| 3668 | if (Record.size() < 2) |
| 3669 | return error(Message: "Invalid inlineasm record" ); |
| 3670 | std::string AsmStr, ConstrStr; |
| 3671 | bool HasSideEffects = Record[0] & 1; |
| 3672 | bool IsAlignStack = (Record[0] >> 1) & 1; |
| 3673 | unsigned AsmDialect = Record[0] >> 2; |
| 3674 | unsigned AsmStrSize = Record[1]; |
| 3675 | if (2+AsmStrSize >= Record.size()) |
| 3676 | return error(Message: "Invalid inlineasm record" ); |
| 3677 | unsigned ConstStrSize = Record[2+AsmStrSize]; |
| 3678 | if (3+AsmStrSize+ConstStrSize > Record.size()) |
| 3679 | return error(Message: "Invalid inlineasm record" ); |
| 3680 | |
| 3681 | for (unsigned i = 0; i != AsmStrSize; ++i) |
| 3682 | AsmStr += (char)Record[2+i]; |
| 3683 | for (unsigned i = 0; i != ConstStrSize; ++i) |
| 3684 | ConstrStr += (char)Record[3+AsmStrSize+i]; |
| 3685 | UpgradeInlineAsmString(AsmStr: &AsmStr); |
| 3686 | if (!CurElemTy) |
| 3687 | return error(Message: "Missing element type for old-style inlineasm" ); |
| 3688 | V = InlineAsm::get(Ty: cast<FunctionType>(Val: CurElemTy), AsmString: AsmStr, Constraints: ConstrStr, |
| 3689 | hasSideEffects: HasSideEffects, isAlignStack: IsAlignStack, |
| 3690 | asmDialect: InlineAsm::AsmDialect(AsmDialect)); |
| 3691 | break; |
| 3692 | } |
| 3693 | // This version adds support for the unwind keyword. |
| 3694 | case bitc::CST_CODE_INLINEASM_OLD3: { |
| 3695 | if (Record.size() < 2) |
| 3696 | return error(Message: "Invalid inlineasm record" ); |
| 3697 | unsigned OpNum = 0; |
| 3698 | std::string AsmStr, ConstrStr; |
| 3699 | bool HasSideEffects = Record[OpNum] & 1; |
| 3700 | bool IsAlignStack = (Record[OpNum] >> 1) & 1; |
| 3701 | unsigned AsmDialect = (Record[OpNum] >> 2) & 1; |
| 3702 | bool CanThrow = (Record[OpNum] >> 3) & 1; |
| 3703 | ++OpNum; |
| 3704 | unsigned AsmStrSize = Record[OpNum]; |
| 3705 | ++OpNum; |
| 3706 | if (OpNum + AsmStrSize >= Record.size()) |
| 3707 | return error(Message: "Invalid inlineasm record" ); |
| 3708 | unsigned ConstStrSize = Record[OpNum + AsmStrSize]; |
| 3709 | if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) |
| 3710 | return error(Message: "Invalid inlineasm record" ); |
| 3711 | |
| 3712 | for (unsigned i = 0; i != AsmStrSize; ++i) |
| 3713 | AsmStr += (char)Record[OpNum + i]; |
| 3714 | ++OpNum; |
| 3715 | for (unsigned i = 0; i != ConstStrSize; ++i) |
| 3716 | ConstrStr += (char)Record[OpNum + AsmStrSize + i]; |
| 3717 | UpgradeInlineAsmString(AsmStr: &AsmStr); |
| 3718 | if (!CurElemTy) |
| 3719 | return error(Message: "Missing element type for old-style inlineasm" ); |
| 3720 | V = InlineAsm::get(Ty: cast<FunctionType>(Val: CurElemTy), AsmString: AsmStr, Constraints: ConstrStr, |
| 3721 | hasSideEffects: HasSideEffects, isAlignStack: IsAlignStack, |
| 3722 | asmDialect: InlineAsm::AsmDialect(AsmDialect), canThrow: CanThrow); |
| 3723 | break; |
| 3724 | } |
| 3725 | // This version adds explicit function type. |
| 3726 | case bitc::CST_CODE_INLINEASM: { |
| 3727 | if (Record.size() < 3) |
| 3728 | return error(Message: "Invalid inlineasm record" ); |
| 3729 | unsigned OpNum = 0; |
| 3730 | auto *FnTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: Record[OpNum])); |
| 3731 | ++OpNum; |
| 3732 | if (!FnTy) |
| 3733 | return error(Message: "Invalid inlineasm record" ); |
| 3734 | std::string AsmStr, ConstrStr; |
| 3735 | bool HasSideEffects = Record[OpNum] & 1; |
| 3736 | bool IsAlignStack = (Record[OpNum] >> 1) & 1; |
| 3737 | unsigned AsmDialect = (Record[OpNum] >> 2) & 1; |
| 3738 | bool CanThrow = (Record[OpNum] >> 3) & 1; |
| 3739 | ++OpNum; |
| 3740 | unsigned AsmStrSize = Record[OpNum]; |
| 3741 | ++OpNum; |
| 3742 | if (OpNum + AsmStrSize >= Record.size()) |
| 3743 | return error(Message: "Invalid inlineasm record" ); |
| 3744 | unsigned ConstStrSize = Record[OpNum + AsmStrSize]; |
| 3745 | if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) |
| 3746 | return error(Message: "Invalid inlineasm record" ); |
| 3747 | |
| 3748 | for (unsigned i = 0; i != AsmStrSize; ++i) |
| 3749 | AsmStr += (char)Record[OpNum + i]; |
| 3750 | ++OpNum; |
| 3751 | for (unsigned i = 0; i != ConstStrSize; ++i) |
| 3752 | ConstrStr += (char)Record[OpNum + AsmStrSize + i]; |
| 3753 | UpgradeInlineAsmString(AsmStr: &AsmStr); |
| 3754 | V = InlineAsm::get(Ty: FnTy, AsmString: AsmStr, Constraints: ConstrStr, hasSideEffects: HasSideEffects, isAlignStack: IsAlignStack, |
| 3755 | asmDialect: InlineAsm::AsmDialect(AsmDialect), canThrow: CanThrow); |
| 3756 | break; |
| 3757 | } |
| 3758 | case bitc::CST_CODE_BLOCKADDRESS:{ |
| 3759 | if (Record.size() < 3) |
| 3760 | return error(Message: "Invalid blockaddress record" ); |
| 3761 | unsigned FnTyID = Record[0]; |
| 3762 | Type *FnTy = getTypeByID(ID: FnTyID); |
| 3763 | if (!FnTy) |
| 3764 | return error(Message: "Invalid blockaddress record" ); |
| 3765 | V = BitcodeConstant::create( |
| 3766 | A&: Alloc, Ty: CurTy, |
| 3767 | Info: {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]}, |
| 3768 | OpIDs: Record[1]); |
| 3769 | break; |
| 3770 | } |
| 3771 | case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: { |
| 3772 | if (Record.size() < 2) |
| 3773 | return error(Message: "Invalid dso_local record" ); |
| 3774 | unsigned GVTyID = Record[0]; |
| 3775 | Type *GVTy = getTypeByID(ID: GVTyID); |
| 3776 | if (!GVTy) |
| 3777 | return error(Message: "Invalid dso_local record" ); |
| 3778 | V = BitcodeConstant::create( |
| 3779 | A&: Alloc, Ty: CurTy, Info: BitcodeConstant::DSOLocalEquivalentOpcode, OpIDs: Record[1]); |
| 3780 | break; |
| 3781 | } |
| 3782 | case bitc::CST_CODE_NO_CFI_VALUE: { |
| 3783 | if (Record.size() < 2) |
| 3784 | return error(Message: "Invalid no_cfi record" ); |
| 3785 | unsigned GVTyID = Record[0]; |
| 3786 | Type *GVTy = getTypeByID(ID: GVTyID); |
| 3787 | if (!GVTy) |
| 3788 | return error(Message: "Invalid no_cfi record" ); |
| 3789 | V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: BitcodeConstant::NoCFIOpcode, |
| 3790 | OpIDs: Record[1]); |
| 3791 | break; |
| 3792 | } |
| 3793 | case bitc::CST_CODE_PTRAUTH: { |
| 3794 | if (Record.size() < 4) |
| 3795 | return error(Message: "Invalid ptrauth record" ); |
| 3796 | // Ptr, Key, Disc, AddrDisc |
| 3797 | V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, |
| 3798 | Info: BitcodeConstant::ConstantPtrAuthOpcode, |
| 3799 | OpIDs: {(unsigned)Record[0], (unsigned)Record[1], |
| 3800 | (unsigned)Record[2], (unsigned)Record[3]}); |
| 3801 | break; |
| 3802 | } |
| 3803 | } |
| 3804 | |
| 3805 | assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID" ); |
| 3806 | if (Error Err = ValueList.assignValue(Idx: NextCstNo, V, TypeID: CurTyID)) |
| 3807 | return Err; |
| 3808 | ++NextCstNo; |
| 3809 | } |
| 3810 | } |
| 3811 | |
| 3812 | Error BitcodeReader::parseUseLists() { |
| 3813 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::USELIST_BLOCK_ID)) |
| 3814 | return Err; |
| 3815 | |
| 3816 | // Read all the records. |
| 3817 | SmallVector<uint64_t, 64> Record; |
| 3818 | |
| 3819 | while (true) { |
| 3820 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 3821 | if (!MaybeEntry) |
| 3822 | return MaybeEntry.takeError(); |
| 3823 | BitstreamEntry Entry = MaybeEntry.get(); |
| 3824 | |
| 3825 | switch (Entry.Kind) { |
| 3826 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 3827 | case BitstreamEntry::Error: |
| 3828 | return error(Message: "Malformed block" ); |
| 3829 | case BitstreamEntry::EndBlock: |
| 3830 | return Error::success(); |
| 3831 | case BitstreamEntry::Record: |
| 3832 | // The interesting case. |
| 3833 | break; |
| 3834 | } |
| 3835 | |
| 3836 | // Read a use list record. |
| 3837 | Record.clear(); |
| 3838 | bool IsBB = false; |
| 3839 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 3840 | if (!MaybeRecord) |
| 3841 | return MaybeRecord.takeError(); |
| 3842 | switch (MaybeRecord.get()) { |
| 3843 | default: // Default behavior: unknown type. |
| 3844 | break; |
| 3845 | case bitc::USELIST_CODE_BB: |
| 3846 | IsBB = true; |
| 3847 | [[fallthrough]]; |
| 3848 | case bitc::USELIST_CODE_DEFAULT: { |
| 3849 | unsigned RecordLength = Record.size(); |
| 3850 | if (RecordLength < 3) |
| 3851 | // Records should have at least an ID and two indexes. |
| 3852 | return error(Message: "Invalid record" ); |
| 3853 | unsigned ID = Record.pop_back_val(); |
| 3854 | |
| 3855 | Value *V; |
| 3856 | if (IsBB) { |
| 3857 | assert(ID < FunctionBBs.size() && "Basic block not found" ); |
| 3858 | V = FunctionBBs[ID]; |
| 3859 | } else |
| 3860 | V = ValueList[ID]; |
| 3861 | |
| 3862 | if (!V->hasUseList()) |
| 3863 | break; |
| 3864 | |
| 3865 | unsigned NumUses = 0; |
| 3866 | SmallDenseMap<const Use *, unsigned, 16> Order; |
| 3867 | for (const Use &U : V->materialized_uses()) { |
| 3868 | if (++NumUses > Record.size()) |
| 3869 | break; |
| 3870 | Order[&U] = Record[NumUses - 1]; |
| 3871 | } |
| 3872 | if (Order.size() != Record.size() || NumUses > Record.size()) |
| 3873 | // Mismatches can happen if the functions are being materialized lazily |
| 3874 | // (out-of-order), or a value has been upgraded. |
| 3875 | break; |
| 3876 | |
| 3877 | V->sortUseList(Cmp: [&](const Use &L, const Use &R) { |
| 3878 | return Order.lookup(Val: &L) < Order.lookup(Val: &R); |
| 3879 | }); |
| 3880 | break; |
| 3881 | } |
| 3882 | } |
| 3883 | } |
| 3884 | } |
| 3885 | |
| 3886 | /// When we see the block for metadata, remember where it is and then skip it. |
| 3887 | /// This lets us lazily deserialize the metadata. |
| 3888 | Error BitcodeReader::rememberAndSkipMetadata() { |
| 3889 | // Save the current stream state. |
| 3890 | uint64_t CurBit = Stream.GetCurrentBitNo(); |
| 3891 | DeferredMetadataInfo.push_back(x: CurBit); |
| 3892 | |
| 3893 | // Skip over the block for now. |
| 3894 | if (Error Err = Stream.SkipBlock()) |
| 3895 | return Err; |
| 3896 | return Error::success(); |
| 3897 | } |
| 3898 | |
| 3899 | Error BitcodeReader::materializeMetadata() { |
| 3900 | for (uint64_t BitPos : DeferredMetadataInfo) { |
| 3901 | // Move the bit stream to the saved position. |
| 3902 | if (Error JumpFailed = Stream.JumpToBit(BitNo: BitPos)) |
| 3903 | return JumpFailed; |
| 3904 | if (Error Err = MDLoader->parseModuleMetadata()) |
| 3905 | return Err; |
| 3906 | } |
| 3907 | |
| 3908 | // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level |
| 3909 | // metadata. Only upgrade if the new option doesn't exist to avoid upgrade |
| 3910 | // multiple times. |
| 3911 | if (!TheModule->getNamedMetadata(Name: "llvm.linker.options" )) { |
| 3912 | if (Metadata *Val = TheModule->getModuleFlag(Key: "Linker Options" )) { |
| 3913 | NamedMDNode *LinkerOpts = |
| 3914 | TheModule->getOrInsertNamedMetadata(Name: "llvm.linker.options" ); |
| 3915 | for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) |
| 3916 | LinkerOpts->addOperand(M: cast<MDNode>(Val: MDOptions)); |
| 3917 | } |
| 3918 | } |
| 3919 | |
| 3920 | DeferredMetadataInfo.clear(); |
| 3921 | return Error::success(); |
| 3922 | } |
| 3923 | |
| 3924 | void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } |
| 3925 | |
| 3926 | /// When we see the block for a function body, remember where it is and then |
| 3927 | /// skip it. This lets us lazily deserialize the functions. |
| 3928 | Error BitcodeReader::rememberAndSkipFunctionBody() { |
| 3929 | // Get the function we are talking about. |
| 3930 | if (FunctionsWithBodies.empty()) |
| 3931 | return error(Message: "Insufficient function protos" ); |
| 3932 | |
| 3933 | Function *Fn = FunctionsWithBodies.back(); |
| 3934 | FunctionsWithBodies.pop_back(); |
| 3935 | |
| 3936 | // Save the current stream state. |
| 3937 | uint64_t CurBit = Stream.GetCurrentBitNo(); |
| 3938 | assert( |
| 3939 | (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && |
| 3940 | "Mismatch between VST and scanned function offsets" ); |
| 3941 | DeferredFunctionInfo[Fn] = CurBit; |
| 3942 | |
| 3943 | // Skip over the function block for now. |
| 3944 | if (Error Err = Stream.SkipBlock()) |
| 3945 | return Err; |
| 3946 | return Error::success(); |
| 3947 | } |
| 3948 | |
| 3949 | Error BitcodeReader::globalCleanup() { |
| 3950 | // Patch the initializers for globals and aliases up. |
| 3951 | if (Error Err = resolveGlobalAndIndirectSymbolInits()) |
| 3952 | return Err; |
| 3953 | if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) |
| 3954 | return error(Message: "Malformed global initializer set" ); |
| 3955 | |
| 3956 | // Look for intrinsic functions which need to be upgraded at some point |
| 3957 | // and functions that need to have their function attributes upgraded. |
| 3958 | for (Function &F : *TheModule) { |
| 3959 | MDLoader->upgradeDebugIntrinsics(F); |
| 3960 | Function *NewFn; |
| 3961 | if (UpgradeIntrinsicFunction(F: &F, NewFn)) |
| 3962 | UpgradedIntrinsics[&F] = NewFn; |
| 3963 | // Look for functions that rely on old function attribute behavior. |
| 3964 | UpgradeFunctionAttributes(F); |
| 3965 | } |
| 3966 | |
| 3967 | // Look for global variables which need to be renamed. |
| 3968 | std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables; |
| 3969 | for (GlobalVariable &GV : TheModule->globals()) |
| 3970 | if (GlobalVariable *Upgraded = UpgradeGlobalVariable(GV: &GV)) |
| 3971 | UpgradedVariables.emplace_back(args: &GV, args&: Upgraded); |
| 3972 | for (auto &Pair : UpgradedVariables) { |
| 3973 | Pair.first->eraseFromParent(); |
| 3974 | TheModule->insertGlobalVariable(GV: Pair.second); |
| 3975 | } |
| 3976 | |
| 3977 | // Force deallocation of memory for these vectors to favor the client that |
| 3978 | // want lazy deserialization. |
| 3979 | std::vector<std::pair<GlobalVariable *, unsigned>>().swap(x&: GlobalInits); |
| 3980 | std::vector<std::pair<GlobalValue *, unsigned>>().swap(x&: IndirectSymbolInits); |
| 3981 | return Error::success(); |
| 3982 | } |
| 3983 | |
| 3984 | /// Support for lazy parsing of function bodies. This is required if we |
| 3985 | /// either have an old bitcode file without a VST forward declaration record, |
| 3986 | /// or if we have an anonymous function being materialized, since anonymous |
| 3987 | /// functions do not have a name and are therefore not in the VST. |
| 3988 | Error BitcodeReader::rememberAndSkipFunctionBodies() { |
| 3989 | if (Error JumpFailed = Stream.JumpToBit(BitNo: NextUnreadBit)) |
| 3990 | return JumpFailed; |
| 3991 | |
| 3992 | if (Stream.AtEndOfStream()) |
| 3993 | return error(Message: "Could not find function in stream" ); |
| 3994 | |
| 3995 | if (!SeenFirstFunctionBody) |
| 3996 | return error(Message: "Trying to materialize functions before seeing function blocks" ); |
| 3997 | |
| 3998 | // An old bitcode file with the symbol table at the end would have |
| 3999 | // finished the parse greedily. |
| 4000 | assert(SeenValueSymbolTable); |
| 4001 | |
| 4002 | while (true) { |
| 4003 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
| 4004 | if (!MaybeEntry) |
| 4005 | return MaybeEntry.takeError(); |
| 4006 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
| 4007 | |
| 4008 | switch (Entry.Kind) { |
| 4009 | default: |
| 4010 | return error(Message: "Expect SubBlock" ); |
| 4011 | case BitstreamEntry::SubBlock: |
| 4012 | switch (Entry.ID) { |
| 4013 | default: |
| 4014 | return error(Message: "Expect function block" ); |
| 4015 | case bitc::FUNCTION_BLOCK_ID: |
| 4016 | if (Error Err = rememberAndSkipFunctionBody()) |
| 4017 | return Err; |
| 4018 | NextUnreadBit = Stream.GetCurrentBitNo(); |
| 4019 | return Error::success(); |
| 4020 | } |
| 4021 | } |
| 4022 | } |
| 4023 | } |
| 4024 | |
| 4025 | Error BitcodeReaderBase::readBlockInfo() { |
| 4026 | Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo = |
| 4027 | Stream.ReadBlockInfoBlock(); |
| 4028 | if (!MaybeNewBlockInfo) |
| 4029 | return MaybeNewBlockInfo.takeError(); |
| 4030 | std::optional<BitstreamBlockInfo> NewBlockInfo = |
| 4031 | std::move(MaybeNewBlockInfo.get()); |
| 4032 | if (!NewBlockInfo) |
| 4033 | return error(Message: "Malformed block" ); |
| 4034 | BlockInfo = std::move(*NewBlockInfo); |
| 4035 | return Error::success(); |
| 4036 | } |
| 4037 | |
| 4038 | Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { |
| 4039 | // v1: [selection_kind, name] |
| 4040 | // v2: [strtab_offset, strtab_size, selection_kind] |
| 4041 | StringRef Name; |
| 4042 | std::tie(args&: Name, args&: Record) = readNameFromStrtab(Record); |
| 4043 | |
| 4044 | if (Record.empty()) |
| 4045 | return error(Message: "Invalid record" ); |
| 4046 | Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Val: Record[0]); |
| 4047 | std::string OldFormatName; |
| 4048 | if (!UseStrtab) { |
| 4049 | if (Record.size() < 2) |
| 4050 | return error(Message: "Invalid record" ); |
| 4051 | unsigned ComdatNameSize = Record[1]; |
| 4052 | if (ComdatNameSize > Record.size() - 2) |
| 4053 | return error(Message: "Comdat name size too large" ); |
| 4054 | OldFormatName.reserve(res_arg: ComdatNameSize); |
| 4055 | for (unsigned i = 0; i != ComdatNameSize; ++i) |
| 4056 | OldFormatName += (char)Record[2 + i]; |
| 4057 | Name = OldFormatName; |
| 4058 | } |
| 4059 | Comdat *C = TheModule->getOrInsertComdat(Name); |
| 4060 | C->setSelectionKind(SK); |
| 4061 | ComdatList.push_back(x: C); |
| 4062 | return Error::success(); |
| 4063 | } |
| 4064 | |
| 4065 | static void inferDSOLocal(GlobalValue *GV) { |
| 4066 | // infer dso_local from linkage and visibility if it is not encoded. |
| 4067 | if (GV->hasLocalLinkage() || |
| 4068 | (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())) |
| 4069 | GV->setDSOLocal(true); |
| 4070 | } |
| 4071 | |
| 4072 | GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) { |
| 4073 | GlobalValue::SanitizerMetadata Meta; |
| 4074 | if (V & (1 << 0)) |
| 4075 | Meta.NoAddress = true; |
| 4076 | if (V & (1 << 1)) |
| 4077 | Meta.NoHWAddress = true; |
| 4078 | if (V & (1 << 2)) |
| 4079 | Meta.Memtag = true; |
| 4080 | if (V & (1 << 3)) |
| 4081 | Meta.IsDynInit = true; |
| 4082 | return Meta; |
| 4083 | } |
| 4084 | |
| 4085 | Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { |
| 4086 | // v1: [pointer type, isconst, initid, linkage, alignment, section, |
| 4087 | // visibility, threadlocal, unnamed_addr, externally_initialized, |
| 4088 | // dllstorageclass, comdat, attributes, preemption specifier, |
| 4089 | // partition strtab offset, partition strtab size] (name in VST) |
| 4090 | // v2: [strtab_offset, strtab_size, v1] |
| 4091 | // v3: [v2, code_model] |
| 4092 | StringRef Name; |
| 4093 | std::tie(args&: Name, args&: Record) = readNameFromStrtab(Record); |
| 4094 | |
| 4095 | if (Record.size() < 6) |
| 4096 | return error(Message: "Invalid record" ); |
| 4097 | unsigned TyID = Record[0]; |
| 4098 | Type *Ty = getTypeByID(ID: TyID); |
| 4099 | if (!Ty) |
| 4100 | return error(Message: "Invalid record" ); |
| 4101 | bool isConstant = Record[1] & 1; |
| 4102 | bool explicitType = Record[1] & 2; |
| 4103 | unsigned AddressSpace; |
| 4104 | if (explicitType) { |
| 4105 | AddressSpace = Record[1] >> 2; |
| 4106 | } else { |
| 4107 | if (!Ty->isPointerTy()) |
| 4108 | return error(Message: "Invalid type for value" ); |
| 4109 | AddressSpace = cast<PointerType>(Val: Ty)->getAddressSpace(); |
| 4110 | TyID = getContainedTypeID(ID: TyID); |
| 4111 | Ty = getTypeByID(ID: TyID); |
| 4112 | if (!Ty) |
| 4113 | return error(Message: "Missing element type for old-style global" ); |
| 4114 | } |
| 4115 | |
| 4116 | uint64_t RawLinkage = Record[3]; |
| 4117 | GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Val: RawLinkage); |
| 4118 | MaybeAlign Alignment; |
| 4119 | if (Error Err = parseAlignmentValue(Exponent: Record[4], Alignment)) |
| 4120 | return Err; |
| 4121 | std::string Section; |
| 4122 | if (Record[5]) { |
| 4123 | if (Record[5] - 1 >= SectionTable.size()) |
| 4124 | return error(Message: "Invalid ID" ); |
| 4125 | Section = SectionTable[Record[5] - 1]; |
| 4126 | } |
| 4127 | GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; |
| 4128 | // Local linkage must have default visibility. |
| 4129 | // auto-upgrade `hidden` and `protected` for old bitcode. |
| 4130 | if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) |
| 4131 | Visibility = getDecodedVisibility(Val: Record[6]); |
| 4132 | |
| 4133 | GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; |
| 4134 | if (Record.size() > 7) |
| 4135 | TLM = getDecodedThreadLocalMode(Val: Record[7]); |
| 4136 | |
| 4137 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; |
| 4138 | if (Record.size() > 8) |
| 4139 | UnnamedAddr = getDecodedUnnamedAddrType(Val: Record[8]); |
| 4140 | |
| 4141 | bool ExternallyInitialized = false; |
| 4142 | if (Record.size() > 9) |
| 4143 | ExternallyInitialized = Record[9]; |
| 4144 | |
| 4145 | GlobalVariable *NewGV = |
| 4146 | new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, |
| 4147 | nullptr, TLM, AddressSpace, ExternallyInitialized); |
| 4148 | if (Alignment) |
| 4149 | NewGV->setAlignment(*Alignment); |
| 4150 | if (!Section.empty()) |
| 4151 | NewGV->setSection(Section); |
| 4152 | NewGV->setVisibility(Visibility); |
| 4153 | NewGV->setUnnamedAddr(UnnamedAddr); |
| 4154 | |
| 4155 | if (Record.size() > 10) { |
| 4156 | // A GlobalValue with local linkage cannot have a DLL storage class. |
| 4157 | if (!NewGV->hasLocalLinkage()) { |
| 4158 | NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Val: Record[10])); |
| 4159 | } |
| 4160 | } else { |
| 4161 | upgradeDLLImportExportLinkage(GV: NewGV, Val: RawLinkage); |
| 4162 | } |
| 4163 | |
| 4164 | ValueList.push_back(V: NewGV, TypeID: getVirtualTypeID(Ty: NewGV->getType(), ChildTypeIDs: TyID)); |
| 4165 | |
| 4166 | // Remember which value to use for the global initializer. |
| 4167 | if (unsigned InitID = Record[2]) |
| 4168 | GlobalInits.push_back(x: std::make_pair(x&: NewGV, y: InitID - 1)); |
| 4169 | |
| 4170 | if (Record.size() > 11) { |
| 4171 | if (unsigned ComdatID = Record[11]) { |
| 4172 | if (ComdatID > ComdatList.size()) |
| 4173 | return error(Message: "Invalid global variable comdat ID" ); |
| 4174 | NewGV->setComdat(ComdatList[ComdatID - 1]); |
| 4175 | } |
| 4176 | } else if (hasImplicitComdat(Val: RawLinkage)) { |
| 4177 | ImplicitComdatObjects.insert(V: NewGV); |
| 4178 | } |
| 4179 | |
| 4180 | if (Record.size() > 12) { |
| 4181 | auto AS = getAttributes(i: Record[12]).getFnAttrs(); |
| 4182 | NewGV->setAttributes(AS); |
| 4183 | } |
| 4184 | |
| 4185 | if (Record.size() > 13) { |
| 4186 | NewGV->setDSOLocal(getDecodedDSOLocal(Val: Record[13])); |
| 4187 | } |
| 4188 | inferDSOLocal(GV: NewGV); |
| 4189 | |
| 4190 | // Check whether we have enough values to read a partition name. |
| 4191 | if (Record.size() > 15) |
| 4192 | NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15])); |
| 4193 | |
| 4194 | if (Record.size() > 16 && Record[16]) { |
| 4195 | llvm::GlobalValue::SanitizerMetadata Meta = |
| 4196 | deserializeSanitizerMetadata(V: Record[16]); |
| 4197 | NewGV->setSanitizerMetadata(Meta); |
| 4198 | } |
| 4199 | |
| 4200 | if (Record.size() > 17 && Record[17]) { |
| 4201 | if (auto CM = getDecodedCodeModel(Val: Record[17])) |
| 4202 | NewGV->setCodeModel(*CM); |
| 4203 | else |
| 4204 | return error(Message: "Invalid global variable code model" ); |
| 4205 | } |
| 4206 | |
| 4207 | return Error::success(); |
| 4208 | } |
| 4209 | |
| 4210 | void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) { |
| 4211 | if (ValueTypeCallback) { |
| 4212 | (*ValueTypeCallback)( |
| 4213 | F, TypeID, [this](unsigned I) { return getTypeByID(ID: I); }, |
| 4214 | [this](unsigned I, unsigned J) { return getContainedTypeID(ID: I, Idx: J); }); |
| 4215 | } |
| 4216 | } |
| 4217 | |
| 4218 | Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { |
| 4219 | // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, |
| 4220 | // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, |
| 4221 | // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST) |
| 4222 | // v2: [strtab_offset, strtab_size, v1] |
| 4223 | StringRef Name; |
| 4224 | std::tie(args&: Name, args&: Record) = readNameFromStrtab(Record); |
| 4225 | |
| 4226 | if (Record.size() < 8) |
| 4227 | return error(Message: "Invalid record" ); |
| 4228 | unsigned FTyID = Record[0]; |
| 4229 | Type *FTy = getTypeByID(ID: FTyID); |
| 4230 | if (!FTy) |
| 4231 | return error(Message: "Invalid record" ); |
| 4232 | if (isa<PointerType>(Val: FTy)) { |
| 4233 | FTyID = getContainedTypeID(ID: FTyID, Idx: 0); |
| 4234 | FTy = getTypeByID(ID: FTyID); |
| 4235 | if (!FTy) |
| 4236 | return error(Message: "Missing element type for old-style function" ); |
| 4237 | } |
| 4238 | |
| 4239 | if (!isa<FunctionType>(Val: FTy)) |
| 4240 | return error(Message: "Invalid type for value" ); |
| 4241 | auto CC = static_cast<CallingConv::ID>(Record[1]); |
| 4242 | if (CC & ~CallingConv::MaxID) |
| 4243 | return error(Message: "Invalid calling convention ID" ); |
| 4244 | |
| 4245 | unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace(); |
| 4246 | if (Record.size() > 16) |
| 4247 | AddrSpace = Record[16]; |
| 4248 | |
| 4249 | Function *Func = |
| 4250 | Function::Create(Ty: cast<FunctionType>(Val: FTy), Linkage: GlobalValue::ExternalLinkage, |
| 4251 | AddrSpace, N: Name, M: TheModule); |
| 4252 | |
| 4253 | assert(Func->getFunctionType() == FTy && |
| 4254 | "Incorrect fully specified type provided for function" ); |
| 4255 | FunctionTypeIDs[Func] = FTyID; |
| 4256 | |
| 4257 | Func->setCallingConv(CC); |
| 4258 | bool isProto = Record[2]; |
| 4259 | uint64_t RawLinkage = Record[3]; |
| 4260 | Func->setLinkage(getDecodedLinkage(Val: RawLinkage)); |
| 4261 | Func->setAttributes(getAttributes(i: Record[4])); |
| 4262 | callValueTypeCallback(F: Func, TypeID: FTyID); |
| 4263 | |
| 4264 | // Upgrade any old-style byval or sret without a type by propagating the |
| 4265 | // argument's pointee type. There should be no opaque pointers where the byval |
| 4266 | // type is implicit. |
| 4267 | for (unsigned i = 0; i != Func->arg_size(); ++i) { |
| 4268 | for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, |
| 4269 | Attribute::InAlloca}) { |
| 4270 | if (!Func->hasParamAttribute(ArgNo: i, Kind)) |
| 4271 | continue; |
| 4272 | |
| 4273 | if (Func->getParamAttribute(ArgNo: i, Kind).getValueAsType()) |
| 4274 | continue; |
| 4275 | |
| 4276 | Func->removeParamAttr(ArgNo: i, Kind); |
| 4277 | |
| 4278 | unsigned ParamTypeID = getContainedTypeID(ID: FTyID, Idx: i + 1); |
| 4279 | Type *PtrEltTy = getPtrElementTypeByID(ID: ParamTypeID); |
| 4280 | if (!PtrEltTy) |
| 4281 | return error(Message: "Missing param element type for attribute upgrade" ); |
| 4282 | |
| 4283 | Attribute NewAttr; |
| 4284 | switch (Kind) { |
| 4285 | case Attribute::ByVal: |
| 4286 | NewAttr = Attribute::getWithByValType(Context, Ty: PtrEltTy); |
| 4287 | break; |
| 4288 | case Attribute::StructRet: |
| 4289 | NewAttr = Attribute::getWithStructRetType(Context, Ty: PtrEltTy); |
| 4290 | break; |
| 4291 | case Attribute::InAlloca: |
| 4292 | NewAttr = Attribute::getWithInAllocaType(Context, Ty: PtrEltTy); |
| 4293 | break; |
| 4294 | default: |
| 4295 | llvm_unreachable("not an upgraded type attribute" ); |
| 4296 | } |
| 4297 | |
| 4298 | Func->addParamAttr(ArgNo: i, Attr: NewAttr); |
| 4299 | } |
| 4300 | } |
| 4301 | |
| 4302 | if (Func->getCallingConv() == CallingConv::X86_INTR && |
| 4303 | !Func->arg_empty() && !Func->hasParamAttribute(ArgNo: 0, Kind: Attribute::ByVal)) { |
| 4304 | unsigned ParamTypeID = getContainedTypeID(ID: FTyID, Idx: 1); |
| 4305 | Type *ByValTy = getPtrElementTypeByID(ID: ParamTypeID); |
| 4306 | if (!ByValTy) |
| 4307 | return error(Message: "Missing param element type for x86_intrcc upgrade" ); |
| 4308 | Attribute NewAttr = Attribute::getWithByValType(Context, Ty: ByValTy); |
| 4309 | Func->addParamAttr(ArgNo: 0, Attr: NewAttr); |
| 4310 | } |
| 4311 | |
| 4312 | MaybeAlign Alignment; |
| 4313 | if (Error Err = parseAlignmentValue(Exponent: Record[5], Alignment)) |
| 4314 | return Err; |
| 4315 | if (Alignment) |
| 4316 | Func->setAlignment(*Alignment); |
| 4317 | if (Record[6]) { |
| 4318 | if (Record[6] - 1 >= SectionTable.size()) |
| 4319 | return error(Message: "Invalid ID" ); |
| 4320 | Func->setSection(SectionTable[Record[6] - 1]); |
| 4321 | } |
| 4322 | // Local linkage must have default visibility. |
| 4323 | // auto-upgrade `hidden` and `protected` for old bitcode. |
| 4324 | if (!Func->hasLocalLinkage()) |
| 4325 | Func->setVisibility(getDecodedVisibility(Val: Record[7])); |
| 4326 | if (Record.size() > 8 && Record[8]) { |
| 4327 | if (Record[8] - 1 >= GCTable.size()) |
| 4328 | return error(Message: "Invalid ID" ); |
| 4329 | Func->setGC(GCTable[Record[8] - 1]); |
| 4330 | } |
| 4331 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; |
| 4332 | if (Record.size() > 9) |
| 4333 | UnnamedAddr = getDecodedUnnamedAddrType(Val: Record[9]); |
| 4334 | Func->setUnnamedAddr(UnnamedAddr); |
| 4335 | |
| 4336 | FunctionOperandInfo OperandInfo = {.F: Func, .PersonalityFn: 0, .Prefix: 0, .Prologue: 0}; |
| 4337 | if (Record.size() > 10) |
| 4338 | OperandInfo.Prologue = Record[10]; |
| 4339 | |
| 4340 | if (Record.size() > 11) { |
| 4341 | // A GlobalValue with local linkage cannot have a DLL storage class. |
| 4342 | if (!Func->hasLocalLinkage()) { |
| 4343 | Func->setDLLStorageClass(getDecodedDLLStorageClass(Val: Record[11])); |
| 4344 | } |
| 4345 | } else { |
| 4346 | upgradeDLLImportExportLinkage(GV: Func, Val: RawLinkage); |
| 4347 | } |
| 4348 | |
| 4349 | if (Record.size() > 12) { |
| 4350 | if (unsigned ComdatID = Record[12]) { |
| 4351 | if (ComdatID > ComdatList.size()) |
| 4352 | return error(Message: "Invalid function comdat ID" ); |
| 4353 | Func->setComdat(ComdatList[ComdatID - 1]); |
| 4354 | } |
| 4355 | } else if (hasImplicitComdat(Val: RawLinkage)) { |
| 4356 | ImplicitComdatObjects.insert(V: Func); |
| 4357 | } |
| 4358 | |
| 4359 | if (Record.size() > 13) |
| 4360 | OperandInfo.Prefix = Record[13]; |
| 4361 | |
| 4362 | if (Record.size() > 14) |
| 4363 | OperandInfo.PersonalityFn = Record[14]; |
| 4364 | |
| 4365 | if (Record.size() > 15) { |
| 4366 | Func->setDSOLocal(getDecodedDSOLocal(Val: Record[15])); |
| 4367 | } |
| 4368 | inferDSOLocal(GV: Func); |
| 4369 | |
| 4370 | // Record[16] is the address space number. |
| 4371 | |
| 4372 | // Check whether we have enough values to read a partition name. Also make |
| 4373 | // sure Strtab has enough values. |
| 4374 | if (Record.size() > 18 && Strtab.data() && |
| 4375 | Record[17] + Record[18] <= Strtab.size()) { |
| 4376 | Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18])); |
| 4377 | } |
| 4378 | |
| 4379 | ValueList.push_back(V: Func, TypeID: getVirtualTypeID(Ty: Func->getType(), ChildTypeIDs: FTyID)); |
| 4380 | |
| 4381 | if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue) |
| 4382 | FunctionOperands.push_back(x: OperandInfo); |
| 4383 | |
| 4384 | // If this is a function with a body, remember the prototype we are |
| 4385 | // creating now, so that we can match up the body with them later. |
| 4386 | if (!isProto) { |
| 4387 | Func->setIsMaterializable(true); |
| 4388 | FunctionsWithBodies.push_back(x: Func); |
| 4389 | DeferredFunctionInfo[Func] = 0; |
| 4390 | } |
| 4391 | return Error::success(); |
| 4392 | } |
| 4393 | |
| 4394 | Error BitcodeReader::parseGlobalIndirectSymbolRecord( |
| 4395 | unsigned BitCode, ArrayRef<uint64_t> Record) { |
| 4396 | // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) |
| 4397 | // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, |
| 4398 | // dllstorageclass, threadlocal, unnamed_addr, |
| 4399 | // preemption specifier] (name in VST) |
| 4400 | // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, |
| 4401 | // visibility, dllstorageclass, threadlocal, unnamed_addr, |
| 4402 | // preemption specifier] (name in VST) |
| 4403 | // v2: [strtab_offset, strtab_size, v1] |
| 4404 | StringRef Name; |
| 4405 | std::tie(args&: Name, args&: Record) = readNameFromStrtab(Record); |
| 4406 | |
| 4407 | bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; |
| 4408 | if (Record.size() < (3 + (unsigned)NewRecord)) |
| 4409 | return error(Message: "Invalid record" ); |
| 4410 | unsigned OpNum = 0; |
| 4411 | unsigned TypeID = Record[OpNum++]; |
| 4412 | Type *Ty = getTypeByID(ID: TypeID); |
| 4413 | if (!Ty) |
| 4414 | return error(Message: "Invalid record" ); |
| 4415 | |
| 4416 | unsigned AddrSpace; |
| 4417 | if (!NewRecord) { |
| 4418 | auto *PTy = dyn_cast<PointerType>(Val: Ty); |
| 4419 | if (!PTy) |
| 4420 | return error(Message: "Invalid type for value" ); |
| 4421 | AddrSpace = PTy->getAddressSpace(); |
| 4422 | TypeID = getContainedTypeID(ID: TypeID); |
| 4423 | Ty = getTypeByID(ID: TypeID); |
| 4424 | if (!Ty) |
| 4425 | return error(Message: "Missing element type for old-style indirect symbol" ); |
| 4426 | } else { |
| 4427 | AddrSpace = Record[OpNum++]; |
| 4428 | } |
| 4429 | |
| 4430 | auto Val = Record[OpNum++]; |
| 4431 | auto Linkage = Record[OpNum++]; |
| 4432 | GlobalValue *NewGA; |
| 4433 | if (BitCode == bitc::MODULE_CODE_ALIAS || |
| 4434 | BitCode == bitc::MODULE_CODE_ALIAS_OLD) |
| 4435 | NewGA = GlobalAlias::create(Ty, AddressSpace: AddrSpace, Linkage: getDecodedLinkage(Val: Linkage), Name, |
| 4436 | Parent: TheModule); |
| 4437 | else |
| 4438 | NewGA = GlobalIFunc::create(Ty, AddressSpace: AddrSpace, Linkage: getDecodedLinkage(Val: Linkage), Name, |
| 4439 | Resolver: nullptr, Parent: TheModule); |
| 4440 | |
| 4441 | // Local linkage must have default visibility. |
| 4442 | // auto-upgrade `hidden` and `protected` for old bitcode. |
| 4443 | if (OpNum != Record.size()) { |
| 4444 | auto VisInd = OpNum++; |
| 4445 | if (!NewGA->hasLocalLinkage()) |
| 4446 | NewGA->setVisibility(getDecodedVisibility(Val: Record[VisInd])); |
| 4447 | } |
| 4448 | if (BitCode == bitc::MODULE_CODE_ALIAS || |
| 4449 | BitCode == bitc::MODULE_CODE_ALIAS_OLD) { |
| 4450 | if (OpNum != Record.size()) { |
| 4451 | auto S = Record[OpNum++]; |
| 4452 | // A GlobalValue with local linkage cannot have a DLL storage class. |
| 4453 | if (!NewGA->hasLocalLinkage()) |
| 4454 | NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Val: S)); |
| 4455 | } |
| 4456 | else |
| 4457 | upgradeDLLImportExportLinkage(GV: NewGA, Val: Linkage); |
| 4458 | if (OpNum != Record.size()) |
| 4459 | NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Val: Record[OpNum++])); |
| 4460 | if (OpNum != Record.size()) |
| 4461 | NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Val: Record[OpNum++])); |
| 4462 | } |
| 4463 | if (OpNum != Record.size()) |
| 4464 | NewGA->setDSOLocal(getDecodedDSOLocal(Val: Record[OpNum++])); |
| 4465 | inferDSOLocal(GV: NewGA); |
| 4466 | |
| 4467 | // Check whether we have enough values to read a partition name. |
| 4468 | if (OpNum + 1 < Record.size()) { |
| 4469 | // Check Strtab has enough values for the partition. |
| 4470 | if (Record[OpNum] + Record[OpNum + 1] > Strtab.size()) |
| 4471 | return error(Message: "Malformed partition, too large." ); |
| 4472 | NewGA->setPartition( |
| 4473 | StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1])); |
| 4474 | } |
| 4475 | |
| 4476 | ValueList.push_back(V: NewGA, TypeID: getVirtualTypeID(Ty: NewGA->getType(), ChildTypeIDs: TypeID)); |
| 4477 | IndirectSymbolInits.push_back(x: std::make_pair(x&: NewGA, y&: Val)); |
| 4478 | return Error::success(); |
| 4479 | } |
| 4480 | |
| 4481 | Error BitcodeReader::parseModule(uint64_t ResumeBit, |
| 4482 | bool ShouldLazyLoadMetadata, |
| 4483 | ParserCallbacks Callbacks) { |
| 4484 | this->ValueTypeCallback = std::move(Callbacks.ValueType); |
| 4485 | if (ResumeBit) { |
| 4486 | if (Error JumpFailed = Stream.JumpToBit(BitNo: ResumeBit)) |
| 4487 | return JumpFailed; |
| 4488 | } else if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID)) |
| 4489 | return Err; |
| 4490 | |
| 4491 | SmallVector<uint64_t, 64> Record; |
| 4492 | |
| 4493 | // Parts of bitcode parsing depend on the datalayout. Make sure we |
| 4494 | // finalize the datalayout before we run any of that code. |
| 4495 | bool ResolvedDataLayout = false; |
| 4496 | // In order to support importing modules with illegal data layout strings, |
| 4497 | // delay parsing the data layout string until after upgrades and overrides |
| 4498 | // have been applied, allowing to fix illegal data layout strings. |
| 4499 | // Initialize to the current module's layout string in case none is specified. |
| 4500 | std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr(); |
| 4501 | |
| 4502 | auto ResolveDataLayout = [&]() -> Error { |
| 4503 | if (ResolvedDataLayout) |
| 4504 | return Error::success(); |
| 4505 | |
| 4506 | // Datalayout and triple can't be parsed after this point. |
| 4507 | ResolvedDataLayout = true; |
| 4508 | |
| 4509 | // Auto-upgrade the layout string |
| 4510 | TentativeDataLayoutStr = llvm::UpgradeDataLayoutString( |
| 4511 | DL: TentativeDataLayoutStr, Triple: TheModule->getTargetTriple().str()); |
| 4512 | |
| 4513 | // Apply override |
| 4514 | if (Callbacks.DataLayout) { |
| 4515 | if (auto LayoutOverride = (*Callbacks.DataLayout)( |
| 4516 | TheModule->getTargetTriple().str(), TentativeDataLayoutStr)) |
| 4517 | TentativeDataLayoutStr = *LayoutOverride; |
| 4518 | } |
| 4519 | |
| 4520 | // Now the layout string is finalized in TentativeDataLayoutStr. Parse it. |
| 4521 | Expected<DataLayout> MaybeDL = DataLayout::parse(LayoutString: TentativeDataLayoutStr); |
| 4522 | if (!MaybeDL) |
| 4523 | return MaybeDL.takeError(); |
| 4524 | |
| 4525 | TheModule->setDataLayout(MaybeDL.get()); |
| 4526 | return Error::success(); |
| 4527 | }; |
| 4528 | |
| 4529 | // Read all the records for this module. |
| 4530 | while (true) { |
| 4531 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
| 4532 | if (!MaybeEntry) |
| 4533 | return MaybeEntry.takeError(); |
| 4534 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
| 4535 | |
| 4536 | switch (Entry.Kind) { |
| 4537 | case BitstreamEntry::Error: |
| 4538 | return error(Message: "Malformed block" ); |
| 4539 | case BitstreamEntry::EndBlock: |
| 4540 | if (Error Err = ResolveDataLayout()) |
| 4541 | return Err; |
| 4542 | return globalCleanup(); |
| 4543 | |
| 4544 | case BitstreamEntry::SubBlock: |
| 4545 | switch (Entry.ID) { |
| 4546 | default: // Skip unknown content. |
| 4547 | if (Error Err = Stream.SkipBlock()) |
| 4548 | return Err; |
| 4549 | break; |
| 4550 | case bitc::BLOCKINFO_BLOCK_ID: |
| 4551 | if (Error Err = readBlockInfo()) |
| 4552 | return Err; |
| 4553 | break; |
| 4554 | case bitc::PARAMATTR_BLOCK_ID: |
| 4555 | if (Error Err = parseAttributeBlock()) |
| 4556 | return Err; |
| 4557 | break; |
| 4558 | case bitc::PARAMATTR_GROUP_BLOCK_ID: |
| 4559 | if (Error Err = parseAttributeGroupBlock()) |
| 4560 | return Err; |
| 4561 | break; |
| 4562 | case bitc::TYPE_BLOCK_ID_NEW: |
| 4563 | if (Error Err = parseTypeTable()) |
| 4564 | return Err; |
| 4565 | break; |
| 4566 | case bitc::VALUE_SYMTAB_BLOCK_ID: |
| 4567 | if (!SeenValueSymbolTable) { |
| 4568 | // Either this is an old form VST without function index and an |
| 4569 | // associated VST forward declaration record (which would have caused |
| 4570 | // the VST to be jumped to and parsed before it was encountered |
| 4571 | // normally in the stream), or there were no function blocks to |
| 4572 | // trigger an earlier parsing of the VST. |
| 4573 | assert(VSTOffset == 0 || FunctionsWithBodies.empty()); |
| 4574 | if (Error Err = parseValueSymbolTable()) |
| 4575 | return Err; |
| 4576 | SeenValueSymbolTable = true; |
| 4577 | } else { |
| 4578 | // We must have had a VST forward declaration record, which caused |
| 4579 | // the parser to jump to and parse the VST earlier. |
| 4580 | assert(VSTOffset > 0); |
| 4581 | if (Error Err = Stream.SkipBlock()) |
| 4582 | return Err; |
| 4583 | } |
| 4584 | break; |
| 4585 | case bitc::CONSTANTS_BLOCK_ID: |
| 4586 | if (Error Err = parseConstants()) |
| 4587 | return Err; |
| 4588 | if (Error Err = resolveGlobalAndIndirectSymbolInits()) |
| 4589 | return Err; |
| 4590 | break; |
| 4591 | case bitc::METADATA_BLOCK_ID: |
| 4592 | if (ShouldLazyLoadMetadata) { |
| 4593 | if (Error Err = rememberAndSkipMetadata()) |
| 4594 | return Err; |
| 4595 | break; |
| 4596 | } |
| 4597 | assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata" ); |
| 4598 | if (Error Err = MDLoader->parseModuleMetadata()) |
| 4599 | return Err; |
| 4600 | break; |
| 4601 | case bitc::METADATA_KIND_BLOCK_ID: |
| 4602 | if (Error Err = MDLoader->parseMetadataKinds()) |
| 4603 | return Err; |
| 4604 | break; |
| 4605 | case bitc::FUNCTION_BLOCK_ID: |
| 4606 | if (Error Err = ResolveDataLayout()) |
| 4607 | return Err; |
| 4608 | |
| 4609 | // If this is the first function body we've seen, reverse the |
| 4610 | // FunctionsWithBodies list. |
| 4611 | if (!SeenFirstFunctionBody) { |
| 4612 | std::reverse(first: FunctionsWithBodies.begin(), last: FunctionsWithBodies.end()); |
| 4613 | if (Error Err = globalCleanup()) |
| 4614 | return Err; |
| 4615 | SeenFirstFunctionBody = true; |
| 4616 | } |
| 4617 | |
| 4618 | if (VSTOffset > 0) { |
| 4619 | // If we have a VST forward declaration record, make sure we |
| 4620 | // parse the VST now if we haven't already. It is needed to |
| 4621 | // set up the DeferredFunctionInfo vector for lazy reading. |
| 4622 | if (!SeenValueSymbolTable) { |
| 4623 | if (Error Err = BitcodeReader::parseValueSymbolTable(Offset: VSTOffset)) |
| 4624 | return Err; |
| 4625 | SeenValueSymbolTable = true; |
| 4626 | // Fall through so that we record the NextUnreadBit below. |
| 4627 | // This is necessary in case we have an anonymous function that |
| 4628 | // is later materialized. Since it will not have a VST entry we |
| 4629 | // need to fall back to the lazy parse to find its offset. |
| 4630 | } else { |
| 4631 | // If we have a VST forward declaration record, but have already |
| 4632 | // parsed the VST (just above, when the first function body was |
| 4633 | // encountered here), then we are resuming the parse after |
| 4634 | // materializing functions. The ResumeBit points to the |
| 4635 | // start of the last function block recorded in the |
| 4636 | // DeferredFunctionInfo map. Skip it. |
| 4637 | if (Error Err = Stream.SkipBlock()) |
| 4638 | return Err; |
| 4639 | continue; |
| 4640 | } |
| 4641 | } |
| 4642 | |
| 4643 | // Support older bitcode files that did not have the function |
| 4644 | // index in the VST, nor a VST forward declaration record, as |
| 4645 | // well as anonymous functions that do not have VST entries. |
| 4646 | // Build the DeferredFunctionInfo vector on the fly. |
| 4647 | if (Error Err = rememberAndSkipFunctionBody()) |
| 4648 | return Err; |
| 4649 | |
| 4650 | // Suspend parsing when we reach the function bodies. Subsequent |
| 4651 | // materialization calls will resume it when necessary. If the bitcode |
| 4652 | // file is old, the symbol table will be at the end instead and will not |
| 4653 | // have been seen yet. In this case, just finish the parse now. |
| 4654 | if (SeenValueSymbolTable) { |
| 4655 | NextUnreadBit = Stream.GetCurrentBitNo(); |
| 4656 | // After the VST has been parsed, we need to make sure intrinsic name |
| 4657 | // are auto-upgraded. |
| 4658 | return globalCleanup(); |
| 4659 | } |
| 4660 | break; |
| 4661 | case bitc::USELIST_BLOCK_ID: |
| 4662 | if (Error Err = parseUseLists()) |
| 4663 | return Err; |
| 4664 | break; |
| 4665 | case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: |
| 4666 | if (Error Err = parseOperandBundleTags()) |
| 4667 | return Err; |
| 4668 | break; |
| 4669 | case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: |
| 4670 | if (Error Err = parseSyncScopeNames()) |
| 4671 | return Err; |
| 4672 | break; |
| 4673 | } |
| 4674 | continue; |
| 4675 | |
| 4676 | case BitstreamEntry::Record: |
| 4677 | // The interesting case. |
| 4678 | break; |
| 4679 | } |
| 4680 | |
| 4681 | // Read a record. |
| 4682 | Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 4683 | if (!MaybeBitCode) |
| 4684 | return MaybeBitCode.takeError(); |
| 4685 | switch (unsigned BitCode = MaybeBitCode.get()) { |
| 4686 | default: break; // Default behavior, ignore unknown content. |
| 4687 | case bitc::MODULE_CODE_VERSION: { |
| 4688 | Expected<unsigned> VersionOrErr = parseVersionRecord(Record); |
| 4689 | if (!VersionOrErr) |
| 4690 | return VersionOrErr.takeError(); |
| 4691 | UseRelativeIDs = *VersionOrErr >= 1; |
| 4692 | break; |
| 4693 | } |
| 4694 | case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] |
| 4695 | if (ResolvedDataLayout) |
| 4696 | return error(Message: "target triple too late in module" ); |
| 4697 | std::string S; |
| 4698 | if (convertToString(Record, Idx: 0, Result&: S)) |
| 4699 | return error(Message: "Invalid record" ); |
| 4700 | TheModule->setTargetTriple(Triple(std::move(S))); |
| 4701 | break; |
| 4702 | } |
| 4703 | case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] |
| 4704 | if (ResolvedDataLayout) |
| 4705 | return error(Message: "datalayout too late in module" ); |
| 4706 | if (convertToString(Record, Idx: 0, Result&: TentativeDataLayoutStr)) |
| 4707 | return error(Message: "Invalid record" ); |
| 4708 | break; |
| 4709 | } |
| 4710 | case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] |
| 4711 | std::string S; |
| 4712 | if (convertToString(Record, Idx: 0, Result&: S)) |
| 4713 | return error(Message: "Invalid record" ); |
| 4714 | TheModule->setModuleInlineAsm(S); |
| 4715 | break; |
| 4716 | } |
| 4717 | case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] |
| 4718 | // Deprecated, but still needed to read old bitcode files. |
| 4719 | std::string S; |
| 4720 | if (convertToString(Record, Idx: 0, Result&: S)) |
| 4721 | return error(Message: "Invalid record" ); |
| 4722 | // Ignore value. |
| 4723 | break; |
| 4724 | } |
| 4725 | case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] |
| 4726 | std::string S; |
| 4727 | if (convertToString(Record, Idx: 0, Result&: S)) |
| 4728 | return error(Message: "Invalid record" ); |
| 4729 | SectionTable.push_back(x: S); |
| 4730 | break; |
| 4731 | } |
| 4732 | case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] |
| 4733 | std::string S; |
| 4734 | if (convertToString(Record, Idx: 0, Result&: S)) |
| 4735 | return error(Message: "Invalid record" ); |
| 4736 | GCTable.push_back(x: S); |
| 4737 | break; |
| 4738 | } |
| 4739 | case bitc::MODULE_CODE_COMDAT: |
| 4740 | if (Error Err = parseComdatRecord(Record)) |
| 4741 | return Err; |
| 4742 | break; |
| 4743 | // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC} |
| 4744 | // written by ThinLinkBitcodeWriter. See |
| 4745 | // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each |
| 4746 | // record |
| 4747 | // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714) |
| 4748 | case bitc::MODULE_CODE_GLOBALVAR: |
| 4749 | if (Error Err = parseGlobalVarRecord(Record)) |
| 4750 | return Err; |
| 4751 | break; |
| 4752 | case bitc::MODULE_CODE_FUNCTION: |
| 4753 | if (Error Err = ResolveDataLayout()) |
| 4754 | return Err; |
| 4755 | if (Error Err = parseFunctionRecord(Record)) |
| 4756 | return Err; |
| 4757 | break; |
| 4758 | case bitc::MODULE_CODE_IFUNC: |
| 4759 | case bitc::MODULE_CODE_ALIAS: |
| 4760 | case bitc::MODULE_CODE_ALIAS_OLD: |
| 4761 | if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) |
| 4762 | return Err; |
| 4763 | break; |
| 4764 | /// MODULE_CODE_VSTOFFSET: [offset] |
| 4765 | case bitc::MODULE_CODE_VSTOFFSET: |
| 4766 | if (Record.empty()) |
| 4767 | return error(Message: "Invalid record" ); |
| 4768 | // Note that we subtract 1 here because the offset is relative to one word |
| 4769 | // before the start of the identification or module block, which was |
| 4770 | // historically always the start of the regular bitcode header. |
| 4771 | VSTOffset = Record[0] - 1; |
| 4772 | break; |
| 4773 | /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] |
| 4774 | case bitc::MODULE_CODE_SOURCE_FILENAME: |
| 4775 | SmallString<128> ValueName; |
| 4776 | if (convertToString(Record, Idx: 0, Result&: ValueName)) |
| 4777 | return error(Message: "Invalid record" ); |
| 4778 | TheModule->setSourceFileName(ValueName); |
| 4779 | break; |
| 4780 | } |
| 4781 | Record.clear(); |
| 4782 | } |
| 4783 | this->ValueTypeCallback = std::nullopt; |
| 4784 | return Error::success(); |
| 4785 | } |
| 4786 | |
| 4787 | Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, |
| 4788 | bool IsImporting, |
| 4789 | ParserCallbacks Callbacks) { |
| 4790 | TheModule = M; |
| 4791 | MetadataLoaderCallbacks MDCallbacks; |
| 4792 | MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); }; |
| 4793 | MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) { |
| 4794 | return getContainedTypeID(ID: I, Idx: J); |
| 4795 | }; |
| 4796 | MDCallbacks.MDType = Callbacks.MDType; |
| 4797 | MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks); |
| 4798 | return parseModule(ResumeBit: 0, ShouldLazyLoadMetadata, Callbacks); |
| 4799 | } |
| 4800 | |
| 4801 | Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { |
| 4802 | if (!isa<PointerType>(Val: PtrType)) |
| 4803 | return error(Message: "Load/Store operand is not a pointer type" ); |
| 4804 | if (!PointerType::isLoadableOrStorableType(ElemTy: ValType)) |
| 4805 | return error(Message: "Cannot load/store from pointer" ); |
| 4806 | return Error::success(); |
| 4807 | } |
| 4808 | |
| 4809 | Error BitcodeReader::propagateAttributeTypes(CallBase *CB, |
| 4810 | ArrayRef<unsigned> ArgTyIDs) { |
| 4811 | AttributeList Attrs = CB->getAttributes(); |
| 4812 | for (unsigned i = 0; i != CB->arg_size(); ++i) { |
| 4813 | for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, |
| 4814 | Attribute::InAlloca}) { |
| 4815 | if (!Attrs.hasParamAttr(ArgNo: i, Kind) || |
| 4816 | Attrs.getParamAttr(ArgNo: i, Kind).getValueAsType()) |
| 4817 | continue; |
| 4818 | |
| 4819 | Type *PtrEltTy = getPtrElementTypeByID(ID: ArgTyIDs[i]); |
| 4820 | if (!PtrEltTy) |
| 4821 | return error(Message: "Missing element type for typed attribute upgrade" ); |
| 4822 | |
| 4823 | Attribute NewAttr; |
| 4824 | switch (Kind) { |
| 4825 | case Attribute::ByVal: |
| 4826 | NewAttr = Attribute::getWithByValType(Context, Ty: PtrEltTy); |
| 4827 | break; |
| 4828 | case Attribute::StructRet: |
| 4829 | NewAttr = Attribute::getWithStructRetType(Context, Ty: PtrEltTy); |
| 4830 | break; |
| 4831 | case Attribute::InAlloca: |
| 4832 | NewAttr = Attribute::getWithInAllocaType(Context, Ty: PtrEltTy); |
| 4833 | break; |
| 4834 | default: |
| 4835 | llvm_unreachable("not an upgraded type attribute" ); |
| 4836 | } |
| 4837 | |
| 4838 | Attrs = Attrs.addParamAttribute(C&: Context, ArgNos: i, A: NewAttr); |
| 4839 | } |
| 4840 | } |
| 4841 | |
| 4842 | if (CB->isInlineAsm()) { |
| 4843 | const InlineAsm *IA = cast<InlineAsm>(Val: CB->getCalledOperand()); |
| 4844 | unsigned ArgNo = 0; |
| 4845 | for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { |
| 4846 | if (!CI.hasArg()) |
| 4847 | continue; |
| 4848 | |
| 4849 | if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) { |
| 4850 | Type *ElemTy = getPtrElementTypeByID(ID: ArgTyIDs[ArgNo]); |
| 4851 | if (!ElemTy) |
| 4852 | return error(Message: "Missing element type for inline asm upgrade" ); |
| 4853 | Attrs = Attrs.addParamAttribute( |
| 4854 | C&: Context, ArgNos: ArgNo, |
| 4855 | A: Attribute::get(Context, Kind: Attribute::ElementType, Ty: ElemTy)); |
| 4856 | } |
| 4857 | |
| 4858 | ArgNo++; |
| 4859 | } |
| 4860 | } |
| 4861 | |
| 4862 | switch (CB->getIntrinsicID()) { |
| 4863 | case Intrinsic::preserve_array_access_index: |
| 4864 | case Intrinsic::preserve_struct_access_index: |
| 4865 | case Intrinsic::aarch64_ldaxr: |
| 4866 | case Intrinsic::aarch64_ldxr: |
| 4867 | case Intrinsic::aarch64_stlxr: |
| 4868 | case Intrinsic::aarch64_stxr: |
| 4869 | case Intrinsic::arm_ldaex: |
| 4870 | case Intrinsic::arm_ldrex: |
| 4871 | case Intrinsic::arm_stlex: |
| 4872 | case Intrinsic::arm_strex: { |
| 4873 | unsigned ArgNo; |
| 4874 | switch (CB->getIntrinsicID()) { |
| 4875 | case Intrinsic::aarch64_stlxr: |
| 4876 | case Intrinsic::aarch64_stxr: |
| 4877 | case Intrinsic::arm_stlex: |
| 4878 | case Intrinsic::arm_strex: |
| 4879 | ArgNo = 1; |
| 4880 | break; |
| 4881 | default: |
| 4882 | ArgNo = 0; |
| 4883 | break; |
| 4884 | } |
| 4885 | if (!Attrs.getParamElementType(ArgNo)) { |
| 4886 | Type *ElTy = getPtrElementTypeByID(ID: ArgTyIDs[ArgNo]); |
| 4887 | if (!ElTy) |
| 4888 | return error(Message: "Missing element type for elementtype upgrade" ); |
| 4889 | Attribute NewAttr = Attribute::get(Context, Kind: Attribute::ElementType, Ty: ElTy); |
| 4890 | Attrs = Attrs.addParamAttribute(C&: Context, ArgNos: ArgNo, A: NewAttr); |
| 4891 | } |
| 4892 | break; |
| 4893 | } |
| 4894 | default: |
| 4895 | break; |
| 4896 | } |
| 4897 | |
| 4898 | CB->setAttributes(Attrs); |
| 4899 | return Error::success(); |
| 4900 | } |
| 4901 | |
| 4902 | /// Lazily parse the specified function body block. |
| 4903 | Error BitcodeReader::parseFunctionBody(Function *F) { |
| 4904 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::FUNCTION_BLOCK_ID)) |
| 4905 | return Err; |
| 4906 | |
| 4907 | // Unexpected unresolved metadata when parsing function. |
| 4908 | if (MDLoader->hasFwdRefs()) |
| 4909 | return error(Message: "Invalid function metadata: incoming forward references" ); |
| 4910 | |
| 4911 | InstructionList.clear(); |
| 4912 | unsigned ModuleValueListSize = ValueList.size(); |
| 4913 | unsigned ModuleMDLoaderSize = MDLoader->size(); |
| 4914 | |
| 4915 | // Add all the function arguments to the value table. |
| 4916 | unsigned ArgNo = 0; |
| 4917 | unsigned FTyID = FunctionTypeIDs[F]; |
| 4918 | for (Argument &I : F->args()) { |
| 4919 | unsigned ArgTyID = getContainedTypeID(ID: FTyID, Idx: ArgNo + 1); |
| 4920 | assert(I.getType() == getTypeByID(ArgTyID) && |
| 4921 | "Incorrect fully specified type for Function Argument" ); |
| 4922 | ValueList.push_back(V: &I, TypeID: ArgTyID); |
| 4923 | ++ArgNo; |
| 4924 | } |
| 4925 | unsigned NextValueNo = ValueList.size(); |
| 4926 | BasicBlock *CurBB = nullptr; |
| 4927 | unsigned CurBBNo = 0; |
| 4928 | // Block into which constant expressions from phi nodes are materialized. |
| 4929 | BasicBlock *PhiConstExprBB = nullptr; |
| 4930 | // Edge blocks for phi nodes into which constant expressions have been |
| 4931 | // expanded. |
| 4932 | SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4> |
| 4933 | ConstExprEdgeBBs; |
| 4934 | |
| 4935 | DebugLoc LastLoc; |
| 4936 | auto getLastInstruction = [&]() -> Instruction * { |
| 4937 | if (CurBB && !CurBB->empty()) |
| 4938 | return &CurBB->back(); |
| 4939 | else if (CurBBNo && FunctionBBs[CurBBNo - 1] && |
| 4940 | !FunctionBBs[CurBBNo - 1]->empty()) |
| 4941 | return &FunctionBBs[CurBBNo - 1]->back(); |
| 4942 | return nullptr; |
| 4943 | }; |
| 4944 | |
| 4945 | std::vector<OperandBundleDef> OperandBundles; |
| 4946 | |
| 4947 | // Read all the records. |
| 4948 | SmallVector<uint64_t, 64> Record; |
| 4949 | |
| 4950 | while (true) { |
| 4951 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
| 4952 | if (!MaybeEntry) |
| 4953 | return MaybeEntry.takeError(); |
| 4954 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
| 4955 | |
| 4956 | switch (Entry.Kind) { |
| 4957 | case BitstreamEntry::Error: |
| 4958 | return error(Message: "Malformed block" ); |
| 4959 | case BitstreamEntry::EndBlock: |
| 4960 | goto OutOfRecordLoop; |
| 4961 | |
| 4962 | case BitstreamEntry::SubBlock: |
| 4963 | switch (Entry.ID) { |
| 4964 | default: // Skip unknown content. |
| 4965 | if (Error Err = Stream.SkipBlock()) |
| 4966 | return Err; |
| 4967 | break; |
| 4968 | case bitc::CONSTANTS_BLOCK_ID: |
| 4969 | if (Error Err = parseConstants()) |
| 4970 | return Err; |
| 4971 | NextValueNo = ValueList.size(); |
| 4972 | break; |
| 4973 | case bitc::VALUE_SYMTAB_BLOCK_ID: |
| 4974 | if (Error Err = parseValueSymbolTable()) |
| 4975 | return Err; |
| 4976 | break; |
| 4977 | case bitc::METADATA_ATTACHMENT_ID: |
| 4978 | if (Error Err = MDLoader->parseMetadataAttachment(F&: *F, InstructionList)) |
| 4979 | return Err; |
| 4980 | break; |
| 4981 | case bitc::METADATA_BLOCK_ID: |
| 4982 | assert(DeferredMetadataInfo.empty() && |
| 4983 | "Must read all module-level metadata before function-level" ); |
| 4984 | if (Error Err = MDLoader->parseFunctionMetadata()) |
| 4985 | return Err; |
| 4986 | break; |
| 4987 | case bitc::USELIST_BLOCK_ID: |
| 4988 | if (Error Err = parseUseLists()) |
| 4989 | return Err; |
| 4990 | break; |
| 4991 | } |
| 4992 | continue; |
| 4993 | |
| 4994 | case BitstreamEntry::Record: |
| 4995 | // The interesting case. |
| 4996 | break; |
| 4997 | } |
| 4998 | |
| 4999 | // Read a record. |
| 5000 | Record.clear(); |
| 5001 | Instruction *I = nullptr; |
| 5002 | unsigned ResTypeID = InvalidTypeID; |
| 5003 | Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 5004 | if (!MaybeBitCode) |
| 5005 | return MaybeBitCode.takeError(); |
| 5006 | switch (unsigned BitCode = MaybeBitCode.get()) { |
| 5007 | default: // Default behavior: reject |
| 5008 | return error(Message: "Invalid value" ); |
| 5009 | case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] |
| 5010 | if (Record.empty() || Record[0] == 0) |
| 5011 | return error(Message: "Invalid record" ); |
| 5012 | // Create all the basic blocks for the function. |
| 5013 | FunctionBBs.resize(new_size: Record[0]); |
| 5014 | |
| 5015 | // See if anything took the address of blocks in this function. |
| 5016 | auto BBFRI = BasicBlockFwdRefs.find(Val: F); |
| 5017 | if (BBFRI == BasicBlockFwdRefs.end()) { |
| 5018 | for (BasicBlock *&BB : FunctionBBs) |
| 5019 | BB = BasicBlock::Create(Context, Name: "" , Parent: F); |
| 5020 | } else { |
| 5021 | auto &BBRefs = BBFRI->second; |
| 5022 | // Check for invalid basic block references. |
| 5023 | if (BBRefs.size() > FunctionBBs.size()) |
| 5024 | return error(Message: "Invalid ID" ); |
| 5025 | assert(!BBRefs.empty() && "Unexpected empty array" ); |
| 5026 | assert(!BBRefs.front() && "Invalid reference to entry block" ); |
| 5027 | for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; |
| 5028 | ++I) |
| 5029 | if (I < RE && BBRefs[I]) { |
| 5030 | BBRefs[I]->insertInto(Parent: F); |
| 5031 | FunctionBBs[I] = BBRefs[I]; |
| 5032 | } else { |
| 5033 | FunctionBBs[I] = BasicBlock::Create(Context, Name: "" , Parent: F); |
| 5034 | } |
| 5035 | |
| 5036 | // Erase from the table. |
| 5037 | BasicBlockFwdRefs.erase(I: BBFRI); |
| 5038 | } |
| 5039 | |
| 5040 | CurBB = FunctionBBs[0]; |
| 5041 | continue; |
| 5042 | } |
| 5043 | |
| 5044 | case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...] |
| 5045 | // The record should not be emitted if it's an empty list. |
| 5046 | if (Record.empty()) |
| 5047 | return error(Message: "Invalid record" ); |
| 5048 | // When we have the RARE case of a BlockAddress Constant that is not |
| 5049 | // scoped to the Function it refers to, we need to conservatively |
| 5050 | // materialize the referred to Function, regardless of whether or not |
| 5051 | // that Function will ultimately be linked, otherwise users of |
| 5052 | // BitcodeReader might start splicing out Function bodies such that we |
| 5053 | // might no longer be able to materialize the BlockAddress since the |
| 5054 | // BasicBlock (and entire body of the Function) the BlockAddress refers |
| 5055 | // to may have been moved. In the case that the user of BitcodeReader |
| 5056 | // decides ultimately not to link the Function body, materializing here |
| 5057 | // could be considered wasteful, but it's better than a deserialization |
| 5058 | // failure as described. This keeps BitcodeReader unaware of complex |
| 5059 | // linkage policy decisions such as those use by LTO, leaving those |
| 5060 | // decisions "one layer up." |
| 5061 | for (uint64_t ValID : Record) |
| 5062 | if (auto *F = dyn_cast<Function>(Val: ValueList[ValID])) |
| 5063 | BackwardRefFunctions.push_back(x: F); |
| 5064 | else |
| 5065 | return error(Message: "Invalid record" ); |
| 5066 | |
| 5067 | continue; |
| 5068 | |
| 5069 | case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN |
| 5070 | // This record indicates that the last instruction is at the same |
| 5071 | // location as the previous instruction with a location. |
| 5072 | I = getLastInstruction(); |
| 5073 | |
| 5074 | if (!I) |
| 5075 | return error(Message: "Invalid record" ); |
| 5076 | I->setDebugLoc(LastLoc); |
| 5077 | I = nullptr; |
| 5078 | continue; |
| 5079 | |
| 5080 | case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] |
| 5081 | I = getLastInstruction(); |
| 5082 | if (!I || Record.size() < 4) |
| 5083 | return error(Message: "Invalid record" ); |
| 5084 | |
| 5085 | unsigned Line = Record[0], Col = Record[1]; |
| 5086 | unsigned ScopeID = Record[2], IAID = Record[3]; |
| 5087 | bool isImplicitCode = Record.size() == 5 && Record[4]; |
| 5088 | |
| 5089 | MDNode *Scope = nullptr, *IA = nullptr; |
| 5090 | if (ScopeID) { |
| 5091 | Scope = dyn_cast_or_null<MDNode>( |
| 5092 | Val: MDLoader->getMetadataFwdRefOrLoad(Idx: ScopeID - 1)); |
| 5093 | if (!Scope) |
| 5094 | return error(Message: "Invalid record" ); |
| 5095 | } |
| 5096 | if (IAID) { |
| 5097 | IA = dyn_cast_or_null<MDNode>( |
| 5098 | Val: MDLoader->getMetadataFwdRefOrLoad(Idx: IAID - 1)); |
| 5099 | if (!IA) |
| 5100 | return error(Message: "Invalid record" ); |
| 5101 | } |
| 5102 | LastLoc = DILocation::get(Context&: Scope->getContext(), Line, Column: Col, Scope, InlinedAt: IA, |
| 5103 | ImplicitCode: isImplicitCode); |
| 5104 | I->setDebugLoc(LastLoc); |
| 5105 | I = nullptr; |
| 5106 | continue; |
| 5107 | } |
| 5108 | case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] |
| 5109 | unsigned OpNum = 0; |
| 5110 | Value *LHS; |
| 5111 | unsigned TypeID; |
| 5112 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: LHS, TypeID, ConstExprInsertBB: CurBB) || |
| 5113 | OpNum+1 > Record.size()) |
| 5114 | return error(Message: "Invalid record" ); |
| 5115 | |
| 5116 | int Opc = getDecodedUnaryOpcode(Val: Record[OpNum++], Ty: LHS->getType()); |
| 5117 | if (Opc == -1) |
| 5118 | return error(Message: "Invalid record" ); |
| 5119 | I = UnaryOperator::Create(Op: (Instruction::UnaryOps)Opc, S: LHS); |
| 5120 | ResTypeID = TypeID; |
| 5121 | InstructionList.push_back(Elt: I); |
| 5122 | if (OpNum < Record.size()) { |
| 5123 | if (isa<FPMathOperator>(Val: I)) { |
| 5124 | FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[OpNum]); |
| 5125 | if (FMF.any()) |
| 5126 | I->setFastMathFlags(FMF); |
| 5127 | } |
| 5128 | } |
| 5129 | break; |
| 5130 | } |
| 5131 | case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] |
| 5132 | unsigned OpNum = 0; |
| 5133 | Value *LHS, *RHS; |
| 5134 | unsigned TypeID; |
| 5135 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: LHS, TypeID, ConstExprInsertBB: CurBB) || |
| 5136 | popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: LHS->getType(), TyID: TypeID, ResVal&: RHS, |
| 5137 | ConstExprInsertBB: CurBB) || |
| 5138 | OpNum+1 > Record.size()) |
| 5139 | return error(Message: "Invalid record" ); |
| 5140 | |
| 5141 | int Opc = getDecodedBinaryOpcode(Val: Record[OpNum++], Ty: LHS->getType()); |
| 5142 | if (Opc == -1) |
| 5143 | return error(Message: "Invalid record" ); |
| 5144 | I = BinaryOperator::Create(Op: (Instruction::BinaryOps)Opc, S1: LHS, S2: RHS); |
| 5145 | ResTypeID = TypeID; |
| 5146 | InstructionList.push_back(Elt: I); |
| 5147 | if (OpNum < Record.size()) { |
| 5148 | if (Opc == Instruction::Add || |
| 5149 | Opc == Instruction::Sub || |
| 5150 | Opc == Instruction::Mul || |
| 5151 | Opc == Instruction::Shl) { |
| 5152 | if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) |
| 5153 | cast<BinaryOperator>(Val: I)->setHasNoSignedWrap(true); |
| 5154 | if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) |
| 5155 | cast<BinaryOperator>(Val: I)->setHasNoUnsignedWrap(true); |
| 5156 | } else if (Opc == Instruction::SDiv || |
| 5157 | Opc == Instruction::UDiv || |
| 5158 | Opc == Instruction::LShr || |
| 5159 | Opc == Instruction::AShr) { |
| 5160 | if (Record[OpNum] & (1 << bitc::PEO_EXACT)) |
| 5161 | cast<BinaryOperator>(Val: I)->setIsExact(true); |
| 5162 | } else if (Opc == Instruction::Or) { |
| 5163 | if (Record[OpNum] & (1 << bitc::PDI_DISJOINT)) |
| 5164 | cast<PossiblyDisjointInst>(Val: I)->setIsDisjoint(true); |
| 5165 | } else if (isa<FPMathOperator>(Val: I)) { |
| 5166 | FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[OpNum]); |
| 5167 | if (FMF.any()) |
| 5168 | I->setFastMathFlags(FMF); |
| 5169 | } |
| 5170 | } |
| 5171 | break; |
| 5172 | } |
| 5173 | case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] |
| 5174 | unsigned OpNum = 0; |
| 5175 | Value *Op; |
| 5176 | unsigned OpTypeID; |
| 5177 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB) || |
| 5178 | OpNum + 1 > Record.size()) |
| 5179 | return error(Message: "Invalid record" ); |
| 5180 | |
| 5181 | ResTypeID = Record[OpNum++]; |
| 5182 | Type *ResTy = getTypeByID(ID: ResTypeID); |
| 5183 | int Opc = getDecodedCastOpcode(Val: Record[OpNum++]); |
| 5184 | |
| 5185 | if (Opc == -1 || !ResTy) |
| 5186 | return error(Message: "Invalid record" ); |
| 5187 | Instruction *Temp = nullptr; |
| 5188 | if ((I = UpgradeBitCastInst(Opc, V: Op, DestTy: ResTy, Temp))) { |
| 5189 | if (Temp) { |
| 5190 | InstructionList.push_back(Elt: Temp); |
| 5191 | assert(CurBB && "No current BB?" ); |
| 5192 | Temp->insertInto(ParentBB: CurBB, It: CurBB->end()); |
| 5193 | } |
| 5194 | } else { |
| 5195 | auto CastOp = (Instruction::CastOps)Opc; |
| 5196 | if (!CastInst::castIsValid(op: CastOp, S: Op, DstTy: ResTy)) |
| 5197 | return error(Message: "Invalid cast" ); |
| 5198 | I = CastInst::Create(CastOp, S: Op, Ty: ResTy); |
| 5199 | } |
| 5200 | |
| 5201 | if (OpNum < Record.size()) { |
| 5202 | if (Opc == Instruction::ZExt || Opc == Instruction::UIToFP) { |
| 5203 | if (Record[OpNum] & (1 << bitc::PNNI_NON_NEG)) |
| 5204 | cast<PossiblyNonNegInst>(Val: I)->setNonNeg(true); |
| 5205 | } else if (Opc == Instruction::Trunc) { |
| 5206 | if (Record[OpNum] & (1 << bitc::TIO_NO_UNSIGNED_WRAP)) |
| 5207 | cast<TruncInst>(Val: I)->setHasNoUnsignedWrap(true); |
| 5208 | if (Record[OpNum] & (1 << bitc::TIO_NO_SIGNED_WRAP)) |
| 5209 | cast<TruncInst>(Val: I)->setHasNoSignedWrap(true); |
| 5210 | } |
| 5211 | if (isa<FPMathOperator>(Val: I)) { |
| 5212 | FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[OpNum]); |
| 5213 | if (FMF.any()) |
| 5214 | I->setFastMathFlags(FMF); |
| 5215 | } |
| 5216 | } |
| 5217 | |
| 5218 | InstructionList.push_back(Elt: I); |
| 5219 | break; |
| 5220 | } |
| 5221 | case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: |
| 5222 | case bitc::FUNC_CODE_INST_GEP_OLD: |
| 5223 | case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] |
| 5224 | unsigned OpNum = 0; |
| 5225 | |
| 5226 | unsigned TyID; |
| 5227 | Type *Ty; |
| 5228 | GEPNoWrapFlags NW; |
| 5229 | |
| 5230 | if (BitCode == bitc::FUNC_CODE_INST_GEP) { |
| 5231 | NW = toGEPNoWrapFlags(Flags: Record[OpNum++]); |
| 5232 | TyID = Record[OpNum++]; |
| 5233 | Ty = getTypeByID(ID: TyID); |
| 5234 | } else { |
| 5235 | if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD) |
| 5236 | NW = GEPNoWrapFlags::inBounds(); |
| 5237 | TyID = InvalidTypeID; |
| 5238 | Ty = nullptr; |
| 5239 | } |
| 5240 | |
| 5241 | Value *BasePtr; |
| 5242 | unsigned BasePtrTypeID; |
| 5243 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: BasePtr, TypeID&: BasePtrTypeID, |
| 5244 | ConstExprInsertBB: CurBB)) |
| 5245 | return error(Message: "Invalid record" ); |
| 5246 | |
| 5247 | if (!Ty) { |
| 5248 | TyID = getContainedTypeID(ID: BasePtrTypeID); |
| 5249 | if (BasePtr->getType()->isVectorTy()) |
| 5250 | TyID = getContainedTypeID(ID: TyID); |
| 5251 | Ty = getTypeByID(ID: TyID); |
| 5252 | } |
| 5253 | |
| 5254 | SmallVector<Value*, 16> GEPIdx; |
| 5255 | while (OpNum != Record.size()) { |
| 5256 | Value *Op; |
| 5257 | unsigned OpTypeID; |
| 5258 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB)) |
| 5259 | return error(Message: "Invalid record" ); |
| 5260 | GEPIdx.push_back(Elt: Op); |
| 5261 | } |
| 5262 | |
| 5263 | auto *GEP = GetElementPtrInst::Create(PointeeType: Ty, Ptr: BasePtr, IdxList: GEPIdx); |
| 5264 | I = GEP; |
| 5265 | |
| 5266 | ResTypeID = TyID; |
| 5267 | if (cast<GEPOperator>(Val: I)->getNumIndices() != 0) { |
| 5268 | auto GTI = std::next(x: gep_type_begin(GEP: I)); |
| 5269 | for (Value *Idx : drop_begin(RangeOrContainer: cast<GEPOperator>(Val: I)->indices())) { |
| 5270 | unsigned SubType = 0; |
| 5271 | if (GTI.isStruct()) { |
| 5272 | ConstantInt *IdxC = |
| 5273 | Idx->getType()->isVectorTy() |
| 5274 | ? cast<ConstantInt>(Val: cast<Constant>(Val: Idx)->getSplatValue()) |
| 5275 | : cast<ConstantInt>(Val: Idx); |
| 5276 | SubType = IdxC->getZExtValue(); |
| 5277 | } |
| 5278 | ResTypeID = getContainedTypeID(ID: ResTypeID, Idx: SubType); |
| 5279 | ++GTI; |
| 5280 | } |
| 5281 | } |
| 5282 | |
| 5283 | // At this point ResTypeID is the result element type. We need a pointer |
| 5284 | // or vector of pointer to it. |
| 5285 | ResTypeID = getVirtualTypeID(Ty: I->getType()->getScalarType(), ChildTypeIDs: ResTypeID); |
| 5286 | if (I->getType()->isVectorTy()) |
| 5287 | ResTypeID = getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: ResTypeID); |
| 5288 | |
| 5289 | InstructionList.push_back(Elt: I); |
| 5290 | GEP->setNoWrapFlags(NW); |
| 5291 | break; |
| 5292 | } |
| 5293 | |
| 5294 | case bitc::FUNC_CODE_INST_EXTRACTVAL: { |
| 5295 | // EXTRACTVAL: [opty, opval, n x indices] |
| 5296 | unsigned OpNum = 0; |
| 5297 | Value *Agg; |
| 5298 | unsigned AggTypeID; |
| 5299 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Agg, TypeID&: AggTypeID, ConstExprInsertBB: CurBB)) |
| 5300 | return error(Message: "Invalid record" ); |
| 5301 | Type *Ty = Agg->getType(); |
| 5302 | |
| 5303 | unsigned RecSize = Record.size(); |
| 5304 | if (OpNum == RecSize) |
| 5305 | return error(Message: "EXTRACTVAL: Invalid instruction with 0 indices" ); |
| 5306 | |
| 5307 | SmallVector<unsigned, 4> ; |
| 5308 | ResTypeID = AggTypeID; |
| 5309 | for (; OpNum != RecSize; ++OpNum) { |
| 5310 | bool IsArray = Ty->isArrayTy(); |
| 5311 | bool IsStruct = Ty->isStructTy(); |
| 5312 | uint64_t Index = Record[OpNum]; |
| 5313 | |
| 5314 | if (!IsStruct && !IsArray) |
| 5315 | return error(Message: "EXTRACTVAL: Invalid type" ); |
| 5316 | if ((unsigned)Index != Index) |
| 5317 | return error(Message: "Invalid value" ); |
| 5318 | if (IsStruct && Index >= Ty->getStructNumElements()) |
| 5319 | return error(Message: "EXTRACTVAL: Invalid struct index" ); |
| 5320 | if (IsArray && Index >= Ty->getArrayNumElements()) |
| 5321 | return error(Message: "EXTRACTVAL: Invalid array index" ); |
| 5322 | EXTRACTVALIdx.push_back(Elt: (unsigned)Index); |
| 5323 | |
| 5324 | if (IsStruct) { |
| 5325 | Ty = Ty->getStructElementType(N: Index); |
| 5326 | ResTypeID = getContainedTypeID(ID: ResTypeID, Idx: Index); |
| 5327 | } else { |
| 5328 | Ty = Ty->getArrayElementType(); |
| 5329 | ResTypeID = getContainedTypeID(ID: ResTypeID); |
| 5330 | } |
| 5331 | } |
| 5332 | |
| 5333 | I = ExtractValueInst::Create(Agg, Idxs: EXTRACTVALIdx); |
| 5334 | InstructionList.push_back(Elt: I); |
| 5335 | break; |
| 5336 | } |
| 5337 | |
| 5338 | case bitc::FUNC_CODE_INST_INSERTVAL: { |
| 5339 | // INSERTVAL: [opty, opval, opty, opval, n x indices] |
| 5340 | unsigned OpNum = 0; |
| 5341 | Value *Agg; |
| 5342 | unsigned AggTypeID; |
| 5343 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Agg, TypeID&: AggTypeID, ConstExprInsertBB: CurBB)) |
| 5344 | return error(Message: "Invalid record" ); |
| 5345 | Value *Val; |
| 5346 | unsigned ValTypeID; |
| 5347 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB)) |
| 5348 | return error(Message: "Invalid record" ); |
| 5349 | |
| 5350 | unsigned RecSize = Record.size(); |
| 5351 | if (OpNum == RecSize) |
| 5352 | return error(Message: "INSERTVAL: Invalid instruction with 0 indices" ); |
| 5353 | |
| 5354 | SmallVector<unsigned, 4> INSERTVALIdx; |
| 5355 | Type *CurTy = Agg->getType(); |
| 5356 | for (; OpNum != RecSize; ++OpNum) { |
| 5357 | bool IsArray = CurTy->isArrayTy(); |
| 5358 | bool IsStruct = CurTy->isStructTy(); |
| 5359 | uint64_t Index = Record[OpNum]; |
| 5360 | |
| 5361 | if (!IsStruct && !IsArray) |
| 5362 | return error(Message: "INSERTVAL: Invalid type" ); |
| 5363 | if ((unsigned)Index != Index) |
| 5364 | return error(Message: "Invalid value" ); |
| 5365 | if (IsStruct && Index >= CurTy->getStructNumElements()) |
| 5366 | return error(Message: "INSERTVAL: Invalid struct index" ); |
| 5367 | if (IsArray && Index >= CurTy->getArrayNumElements()) |
| 5368 | return error(Message: "INSERTVAL: Invalid array index" ); |
| 5369 | |
| 5370 | INSERTVALIdx.push_back(Elt: (unsigned)Index); |
| 5371 | if (IsStruct) |
| 5372 | CurTy = CurTy->getStructElementType(N: Index); |
| 5373 | else |
| 5374 | CurTy = CurTy->getArrayElementType(); |
| 5375 | } |
| 5376 | |
| 5377 | if (CurTy != Val->getType()) |
| 5378 | return error(Message: "Inserted value type doesn't match aggregate type" ); |
| 5379 | |
| 5380 | I = InsertValueInst::Create(Agg, Val, Idxs: INSERTVALIdx); |
| 5381 | ResTypeID = AggTypeID; |
| 5382 | InstructionList.push_back(Elt: I); |
| 5383 | break; |
| 5384 | } |
| 5385 | |
| 5386 | case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] |
| 5387 | // obsolete form of select |
| 5388 | // handles select i1 ... in old bitcode |
| 5389 | unsigned OpNum = 0; |
| 5390 | Value *TrueVal, *FalseVal, *Cond; |
| 5391 | unsigned TypeID; |
| 5392 | Type *CondType = Type::getInt1Ty(C&: Context); |
| 5393 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: TrueVal, TypeID, |
| 5394 | ConstExprInsertBB: CurBB) || |
| 5395 | popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: TrueVal->getType(), TyID: TypeID, |
| 5396 | ResVal&: FalseVal, ConstExprInsertBB: CurBB) || |
| 5397 | popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: CondType, |
| 5398 | TyID: getVirtualTypeID(Ty: CondType), ResVal&: Cond, ConstExprInsertBB: CurBB)) |
| 5399 | return error(Message: "Invalid record" ); |
| 5400 | |
| 5401 | I = SelectInst::Create(C: Cond, S1: TrueVal, S2: FalseVal); |
| 5402 | ResTypeID = TypeID; |
| 5403 | InstructionList.push_back(Elt: I); |
| 5404 | break; |
| 5405 | } |
| 5406 | |
| 5407 | case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] |
| 5408 | // new form of select |
| 5409 | // handles select i1 or select [N x i1] |
| 5410 | unsigned OpNum = 0; |
| 5411 | Value *TrueVal, *FalseVal, *Cond; |
| 5412 | unsigned ValTypeID, CondTypeID; |
| 5413 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: TrueVal, TypeID&: ValTypeID, |
| 5414 | ConstExprInsertBB: CurBB) || |
| 5415 | popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: TrueVal->getType(), TyID: ValTypeID, |
| 5416 | ResVal&: FalseVal, ConstExprInsertBB: CurBB) || |
| 5417 | getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Cond, TypeID&: CondTypeID, ConstExprInsertBB: CurBB)) |
| 5418 | return error(Message: "Invalid record" ); |
| 5419 | |
| 5420 | // select condition can be either i1 or [N x i1] |
| 5421 | if (VectorType* vector_type = |
| 5422 | dyn_cast<VectorType>(Val: Cond->getType())) { |
| 5423 | // expect <n x i1> |
| 5424 | if (vector_type->getElementType() != Type::getInt1Ty(C&: Context)) |
| 5425 | return error(Message: "Invalid type for value" ); |
| 5426 | } else { |
| 5427 | // expect i1 |
| 5428 | if (Cond->getType() != Type::getInt1Ty(C&: Context)) |
| 5429 | return error(Message: "Invalid type for value" ); |
| 5430 | } |
| 5431 | |
| 5432 | I = SelectInst::Create(C: Cond, S1: TrueVal, S2: FalseVal); |
| 5433 | ResTypeID = ValTypeID; |
| 5434 | InstructionList.push_back(Elt: I); |
| 5435 | if (OpNum < Record.size() && isa<FPMathOperator>(Val: I)) { |
| 5436 | FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[OpNum]); |
| 5437 | if (FMF.any()) |
| 5438 | I->setFastMathFlags(FMF); |
| 5439 | } |
| 5440 | break; |
| 5441 | } |
| 5442 | |
| 5443 | case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] |
| 5444 | unsigned OpNum = 0; |
| 5445 | Value *Vec, *Idx; |
| 5446 | unsigned VecTypeID, IdxTypeID; |
| 5447 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Vec, TypeID&: VecTypeID, ConstExprInsertBB: CurBB) || |
| 5448 | getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Idx, TypeID&: IdxTypeID, ConstExprInsertBB: CurBB)) |
| 5449 | return error(Message: "Invalid record" ); |
| 5450 | if (!Vec->getType()->isVectorTy()) |
| 5451 | return error(Message: "Invalid type for value" ); |
| 5452 | I = ExtractElementInst::Create(Vec, Idx); |
| 5453 | ResTypeID = getContainedTypeID(ID: VecTypeID); |
| 5454 | InstructionList.push_back(Elt: I); |
| 5455 | break; |
| 5456 | } |
| 5457 | |
| 5458 | case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] |
| 5459 | unsigned OpNum = 0; |
| 5460 | Value *Vec, *Elt, *Idx; |
| 5461 | unsigned VecTypeID, IdxTypeID; |
| 5462 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Vec, TypeID&: VecTypeID, ConstExprInsertBB: CurBB)) |
| 5463 | return error(Message: "Invalid record" ); |
| 5464 | if (!Vec->getType()->isVectorTy()) |
| 5465 | return error(Message: "Invalid type for value" ); |
| 5466 | if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, |
| 5467 | Ty: cast<VectorType>(Val: Vec->getType())->getElementType(), |
| 5468 | TyID: getContainedTypeID(ID: VecTypeID), ResVal&: Elt, ConstExprInsertBB: CurBB) || |
| 5469 | getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Idx, TypeID&: IdxTypeID, ConstExprInsertBB: CurBB)) |
| 5470 | return error(Message: "Invalid record" ); |
| 5471 | I = InsertElementInst::Create(Vec, NewElt: Elt, Idx); |
| 5472 | ResTypeID = VecTypeID; |
| 5473 | InstructionList.push_back(Elt: I); |
| 5474 | break; |
| 5475 | } |
| 5476 | |
| 5477 | case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] |
| 5478 | unsigned OpNum = 0; |
| 5479 | Value *Vec1, *Vec2, *Mask; |
| 5480 | unsigned Vec1TypeID; |
| 5481 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Vec1, TypeID&: Vec1TypeID, |
| 5482 | ConstExprInsertBB: CurBB) || |
| 5483 | popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: Vec1->getType(), TyID: Vec1TypeID, |
| 5484 | ResVal&: Vec2, ConstExprInsertBB: CurBB)) |
| 5485 | return error(Message: "Invalid record" ); |
| 5486 | |
| 5487 | unsigned MaskTypeID; |
| 5488 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Mask, TypeID&: MaskTypeID, ConstExprInsertBB: CurBB)) |
| 5489 | return error(Message: "Invalid record" ); |
| 5490 | if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) |
| 5491 | return error(Message: "Invalid type for value" ); |
| 5492 | |
| 5493 | I = new ShuffleVectorInst(Vec1, Vec2, Mask); |
| 5494 | ResTypeID = |
| 5495 | getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: getContainedTypeID(ID: Vec1TypeID)); |
| 5496 | InstructionList.push_back(Elt: I); |
| 5497 | break; |
| 5498 | } |
| 5499 | |
| 5500 | case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] |
| 5501 | // Old form of ICmp/FCmp returning bool |
| 5502 | // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were |
| 5503 | // both legal on vectors but had different behaviour. |
| 5504 | case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] |
| 5505 | // FCmp/ICmp returning bool or vector of bool |
| 5506 | |
| 5507 | unsigned OpNum = 0; |
| 5508 | Value *LHS, *RHS; |
| 5509 | unsigned LHSTypeID; |
| 5510 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: LHS, TypeID&: LHSTypeID, ConstExprInsertBB: CurBB) || |
| 5511 | popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: LHS->getType(), TyID: LHSTypeID, ResVal&: RHS, |
| 5512 | ConstExprInsertBB: CurBB)) |
| 5513 | return error(Message: "Invalid record" ); |
| 5514 | |
| 5515 | if (OpNum >= Record.size()) |
| 5516 | return error( |
| 5517 | Message: "Invalid record: operand number exceeded available operands" ); |
| 5518 | |
| 5519 | CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]); |
| 5520 | bool IsFP = LHS->getType()->isFPOrFPVectorTy(); |
| 5521 | FastMathFlags FMF; |
| 5522 | if (IsFP && Record.size() > OpNum+1) |
| 5523 | FMF = getDecodedFastMathFlags(Val: Record[++OpNum]); |
| 5524 | |
| 5525 | if (IsFP) { |
| 5526 | if (!CmpInst::isFPPredicate(P: PredVal)) |
| 5527 | return error(Message: "Invalid fcmp predicate" ); |
| 5528 | I = new FCmpInst(PredVal, LHS, RHS); |
| 5529 | } else { |
| 5530 | if (!CmpInst::isIntPredicate(P: PredVal)) |
| 5531 | return error(Message: "Invalid icmp predicate" ); |
| 5532 | I = new ICmpInst(PredVal, LHS, RHS); |
| 5533 | if (Record.size() > OpNum + 1 && |
| 5534 | (Record[++OpNum] & (1 << bitc::ICMP_SAME_SIGN))) |
| 5535 | cast<ICmpInst>(Val: I)->setSameSign(); |
| 5536 | } |
| 5537 | |
| 5538 | if (OpNum + 1 != Record.size()) |
| 5539 | return error(Message: "Invalid record" ); |
| 5540 | |
| 5541 | ResTypeID = getVirtualTypeID(Ty: I->getType()->getScalarType()); |
| 5542 | if (LHS->getType()->isVectorTy()) |
| 5543 | ResTypeID = getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: ResTypeID); |
| 5544 | |
| 5545 | if (FMF.any()) |
| 5546 | I->setFastMathFlags(FMF); |
| 5547 | InstructionList.push_back(Elt: I); |
| 5548 | break; |
| 5549 | } |
| 5550 | |
| 5551 | case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] |
| 5552 | { |
| 5553 | unsigned Size = Record.size(); |
| 5554 | if (Size == 0) { |
| 5555 | I = ReturnInst::Create(C&: Context); |
| 5556 | InstructionList.push_back(Elt: I); |
| 5557 | break; |
| 5558 | } |
| 5559 | |
| 5560 | unsigned OpNum = 0; |
| 5561 | Value *Op = nullptr; |
| 5562 | unsigned OpTypeID; |
| 5563 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB)) |
| 5564 | return error(Message: "Invalid record" ); |
| 5565 | if (OpNum != Record.size()) |
| 5566 | return error(Message: "Invalid record" ); |
| 5567 | |
| 5568 | I = ReturnInst::Create(C&: Context, retVal: Op); |
| 5569 | InstructionList.push_back(Elt: I); |
| 5570 | break; |
| 5571 | } |
| 5572 | case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] |
| 5573 | if (Record.size() != 1 && Record.size() != 3) |
| 5574 | return error(Message: "Invalid record" ); |
| 5575 | BasicBlock *TrueDest = getBasicBlock(ID: Record[0]); |
| 5576 | if (!TrueDest) |
| 5577 | return error(Message: "Invalid record" ); |
| 5578 | |
| 5579 | if (Record.size() == 1) { |
| 5580 | I = BranchInst::Create(IfTrue: TrueDest); |
| 5581 | InstructionList.push_back(Elt: I); |
| 5582 | } |
| 5583 | else { |
| 5584 | BasicBlock *FalseDest = getBasicBlock(ID: Record[1]); |
| 5585 | Type *CondType = Type::getInt1Ty(C&: Context); |
| 5586 | Value *Cond = getValue(Record, Slot: 2, InstNum: NextValueNo, Ty: CondType, |
| 5587 | TyID: getVirtualTypeID(Ty: CondType), ConstExprInsertBB: CurBB); |
| 5588 | if (!FalseDest || !Cond) |
| 5589 | return error(Message: "Invalid record" ); |
| 5590 | I = BranchInst::Create(IfTrue: TrueDest, IfFalse: FalseDest, Cond); |
| 5591 | InstructionList.push_back(Elt: I); |
| 5592 | } |
| 5593 | break; |
| 5594 | } |
| 5595 | case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] |
| 5596 | if (Record.size() != 1 && Record.size() != 2) |
| 5597 | return error(Message: "Invalid record" ); |
| 5598 | unsigned Idx = 0; |
| 5599 | Type *TokenTy = Type::getTokenTy(C&: Context); |
| 5600 | Value *CleanupPad = getValue(Record, Slot: Idx++, InstNum: NextValueNo, Ty: TokenTy, |
| 5601 | TyID: getVirtualTypeID(Ty: TokenTy), ConstExprInsertBB: CurBB); |
| 5602 | if (!CleanupPad) |
| 5603 | return error(Message: "Invalid record" ); |
| 5604 | BasicBlock *UnwindDest = nullptr; |
| 5605 | if (Record.size() == 2) { |
| 5606 | UnwindDest = getBasicBlock(ID: Record[Idx++]); |
| 5607 | if (!UnwindDest) |
| 5608 | return error(Message: "Invalid record" ); |
| 5609 | } |
| 5610 | |
| 5611 | I = CleanupReturnInst::Create(CleanupPad, UnwindBB: UnwindDest); |
| 5612 | InstructionList.push_back(Elt: I); |
| 5613 | break; |
| 5614 | } |
| 5615 | case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] |
| 5616 | if (Record.size() != 2) |
| 5617 | return error(Message: "Invalid record" ); |
| 5618 | unsigned Idx = 0; |
| 5619 | Type *TokenTy = Type::getTokenTy(C&: Context); |
| 5620 | Value *CatchPad = getValue(Record, Slot: Idx++, InstNum: NextValueNo, Ty: TokenTy, |
| 5621 | TyID: getVirtualTypeID(Ty: TokenTy), ConstExprInsertBB: CurBB); |
| 5622 | if (!CatchPad) |
| 5623 | return error(Message: "Invalid record" ); |
| 5624 | BasicBlock *BB = getBasicBlock(ID: Record[Idx++]); |
| 5625 | if (!BB) |
| 5626 | return error(Message: "Invalid record" ); |
| 5627 | |
| 5628 | I = CatchReturnInst::Create(CatchPad, BB); |
| 5629 | InstructionList.push_back(Elt: I); |
| 5630 | break; |
| 5631 | } |
| 5632 | case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] |
| 5633 | // We must have, at minimum, the outer scope and the number of arguments. |
| 5634 | if (Record.size() < 2) |
| 5635 | return error(Message: "Invalid record" ); |
| 5636 | |
| 5637 | unsigned Idx = 0; |
| 5638 | |
| 5639 | Type *TokenTy = Type::getTokenTy(C&: Context); |
| 5640 | Value *ParentPad = getValue(Record, Slot: Idx++, InstNum: NextValueNo, Ty: TokenTy, |
| 5641 | TyID: getVirtualTypeID(Ty: TokenTy), ConstExprInsertBB: CurBB); |
| 5642 | if (!ParentPad) |
| 5643 | return error(Message: "Invalid record" ); |
| 5644 | |
| 5645 | unsigned NumHandlers = Record[Idx++]; |
| 5646 | |
| 5647 | SmallVector<BasicBlock *, 2> Handlers; |
| 5648 | for (unsigned Op = 0; Op != NumHandlers; ++Op) { |
| 5649 | BasicBlock *BB = getBasicBlock(ID: Record[Idx++]); |
| 5650 | if (!BB) |
| 5651 | return error(Message: "Invalid record" ); |
| 5652 | Handlers.push_back(Elt: BB); |
| 5653 | } |
| 5654 | |
| 5655 | BasicBlock *UnwindDest = nullptr; |
| 5656 | if (Idx + 1 == Record.size()) { |
| 5657 | UnwindDest = getBasicBlock(ID: Record[Idx++]); |
| 5658 | if (!UnwindDest) |
| 5659 | return error(Message: "Invalid record" ); |
| 5660 | } |
| 5661 | |
| 5662 | if (Record.size() != Idx) |
| 5663 | return error(Message: "Invalid record" ); |
| 5664 | |
| 5665 | auto *CatchSwitch = |
| 5666 | CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); |
| 5667 | for (BasicBlock *Handler : Handlers) |
| 5668 | CatchSwitch->addHandler(Dest: Handler); |
| 5669 | I = CatchSwitch; |
| 5670 | ResTypeID = getVirtualTypeID(Ty: I->getType()); |
| 5671 | InstructionList.push_back(Elt: I); |
| 5672 | break; |
| 5673 | } |
| 5674 | case bitc::FUNC_CODE_INST_CATCHPAD: |
| 5675 | case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] |
| 5676 | // We must have, at minimum, the outer scope and the number of arguments. |
| 5677 | if (Record.size() < 2) |
| 5678 | return error(Message: "Invalid record" ); |
| 5679 | |
| 5680 | unsigned Idx = 0; |
| 5681 | |
| 5682 | Type *TokenTy = Type::getTokenTy(C&: Context); |
| 5683 | Value *ParentPad = getValue(Record, Slot: Idx++, InstNum: NextValueNo, Ty: TokenTy, |
| 5684 | TyID: getVirtualTypeID(Ty: TokenTy), ConstExprInsertBB: CurBB); |
| 5685 | if (!ParentPad) |
| 5686 | return error(Message: "Invald record" ); |
| 5687 | |
| 5688 | unsigned NumArgOperands = Record[Idx++]; |
| 5689 | |
| 5690 | SmallVector<Value *, 2> Args; |
| 5691 | for (unsigned Op = 0; Op != NumArgOperands; ++Op) { |
| 5692 | Value *Val; |
| 5693 | unsigned ValTypeID; |
| 5694 | if (getValueTypePair(Record, Slot&: Idx, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: nullptr)) |
| 5695 | return error(Message: "Invalid record" ); |
| 5696 | Args.push_back(Elt: Val); |
| 5697 | } |
| 5698 | |
| 5699 | if (Record.size() != Idx) |
| 5700 | return error(Message: "Invalid record" ); |
| 5701 | |
| 5702 | if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) |
| 5703 | I = CleanupPadInst::Create(ParentPad, Args); |
| 5704 | else |
| 5705 | I = CatchPadInst::Create(CatchSwitch: ParentPad, Args); |
| 5706 | ResTypeID = getVirtualTypeID(Ty: I->getType()); |
| 5707 | InstructionList.push_back(Elt: I); |
| 5708 | break; |
| 5709 | } |
| 5710 | case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] |
| 5711 | // Check magic |
| 5712 | if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { |
| 5713 | // "New" SwitchInst format with case ranges. The changes to write this |
| 5714 | // format were reverted but we still recognize bitcode that uses it. |
| 5715 | // Hopefully someday we will have support for case ranges and can use |
| 5716 | // this format again. |
| 5717 | |
| 5718 | unsigned OpTyID = Record[1]; |
| 5719 | Type *OpTy = getTypeByID(ID: OpTyID); |
| 5720 | unsigned ValueBitWidth = cast<IntegerType>(Val: OpTy)->getBitWidth(); |
| 5721 | |
| 5722 | Value *Cond = getValue(Record, Slot: 2, InstNum: NextValueNo, Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB); |
| 5723 | BasicBlock *Default = getBasicBlock(ID: Record[3]); |
| 5724 | if (!OpTy || !Cond || !Default) |
| 5725 | return error(Message: "Invalid record" ); |
| 5726 | |
| 5727 | unsigned NumCases = Record[4]; |
| 5728 | |
| 5729 | SwitchInst *SI = SwitchInst::Create(Value: Cond, Default, NumCases); |
| 5730 | InstructionList.push_back(Elt: SI); |
| 5731 | |
| 5732 | unsigned CurIdx = 5; |
| 5733 | for (unsigned i = 0; i != NumCases; ++i) { |
| 5734 | SmallVector<ConstantInt*, 1> CaseVals; |
| 5735 | unsigned NumItems = Record[CurIdx++]; |
| 5736 | for (unsigned ci = 0; ci != NumItems; ++ci) { |
| 5737 | bool isSingleNumber = Record[CurIdx++]; |
| 5738 | |
| 5739 | APInt Low; |
| 5740 | unsigned ActiveWords = 1; |
| 5741 | if (ValueBitWidth > 64) |
| 5742 | ActiveWords = Record[CurIdx++]; |
| 5743 | Low = readWideAPInt(Vals: ArrayRef(&Record[CurIdx], ActiveWords), |
| 5744 | TypeBits: ValueBitWidth); |
| 5745 | CurIdx += ActiveWords; |
| 5746 | |
| 5747 | if (!isSingleNumber) { |
| 5748 | ActiveWords = 1; |
| 5749 | if (ValueBitWidth > 64) |
| 5750 | ActiveWords = Record[CurIdx++]; |
| 5751 | APInt High = readWideAPInt(Vals: ArrayRef(&Record[CurIdx], ActiveWords), |
| 5752 | TypeBits: ValueBitWidth); |
| 5753 | CurIdx += ActiveWords; |
| 5754 | |
| 5755 | // FIXME: It is not clear whether values in the range should be |
| 5756 | // compared as signed or unsigned values. The partially |
| 5757 | // implemented changes that used this format in the past used |
| 5758 | // unsigned comparisons. |
| 5759 | for ( ; Low.ule(RHS: High); ++Low) |
| 5760 | CaseVals.push_back(Elt: ConstantInt::get(Context, V: Low)); |
| 5761 | } else |
| 5762 | CaseVals.push_back(Elt: ConstantInt::get(Context, V: Low)); |
| 5763 | } |
| 5764 | BasicBlock *DestBB = getBasicBlock(ID: Record[CurIdx++]); |
| 5765 | for (ConstantInt *Cst : CaseVals) |
| 5766 | SI->addCase(OnVal: Cst, Dest: DestBB); |
| 5767 | } |
| 5768 | I = SI; |
| 5769 | break; |
| 5770 | } |
| 5771 | |
| 5772 | // Old SwitchInst format without case ranges. |
| 5773 | |
| 5774 | if (Record.size() < 3 || (Record.size() & 1) == 0) |
| 5775 | return error(Message: "Invalid record" ); |
| 5776 | unsigned OpTyID = Record[0]; |
| 5777 | Type *OpTy = getTypeByID(ID: OpTyID); |
| 5778 | Value *Cond = getValue(Record, Slot: 1, InstNum: NextValueNo, Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB); |
| 5779 | BasicBlock *Default = getBasicBlock(ID: Record[2]); |
| 5780 | if (!OpTy || !Cond || !Default) |
| 5781 | return error(Message: "Invalid record" ); |
| 5782 | unsigned NumCases = (Record.size()-3)/2; |
| 5783 | SwitchInst *SI = SwitchInst::Create(Value: Cond, Default, NumCases); |
| 5784 | InstructionList.push_back(Elt: SI); |
| 5785 | for (unsigned i = 0, e = NumCases; i != e; ++i) { |
| 5786 | ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>( |
| 5787 | Val: getFnValueByID(ID: Record[3+i*2], Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: nullptr)); |
| 5788 | BasicBlock *DestBB = getBasicBlock(ID: Record[1+3+i*2]); |
| 5789 | if (!CaseVal || !DestBB) { |
| 5790 | delete SI; |
| 5791 | return error(Message: "Invalid record" ); |
| 5792 | } |
| 5793 | SI->addCase(OnVal: CaseVal, Dest: DestBB); |
| 5794 | } |
| 5795 | I = SI; |
| 5796 | break; |
| 5797 | } |
| 5798 | case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] |
| 5799 | if (Record.size() < 2) |
| 5800 | return error(Message: "Invalid record" ); |
| 5801 | unsigned OpTyID = Record[0]; |
| 5802 | Type *OpTy = getTypeByID(ID: OpTyID); |
| 5803 | Value *Address = getValue(Record, Slot: 1, InstNum: NextValueNo, Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB); |
| 5804 | if (!OpTy || !Address) |
| 5805 | return error(Message: "Invalid record" ); |
| 5806 | unsigned NumDests = Record.size()-2; |
| 5807 | IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); |
| 5808 | InstructionList.push_back(Elt: IBI); |
| 5809 | for (unsigned i = 0, e = NumDests; i != e; ++i) { |
| 5810 | if (BasicBlock *DestBB = getBasicBlock(ID: Record[2+i])) { |
| 5811 | IBI->addDestination(Dest: DestBB); |
| 5812 | } else { |
| 5813 | delete IBI; |
| 5814 | return error(Message: "Invalid record" ); |
| 5815 | } |
| 5816 | } |
| 5817 | I = IBI; |
| 5818 | break; |
| 5819 | } |
| 5820 | |
| 5821 | case bitc::FUNC_CODE_INST_INVOKE: { |
| 5822 | // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] |
| 5823 | if (Record.size() < 4) |
| 5824 | return error(Message: "Invalid record" ); |
| 5825 | unsigned OpNum = 0; |
| 5826 | AttributeList PAL = getAttributes(i: Record[OpNum++]); |
| 5827 | unsigned CCInfo = Record[OpNum++]; |
| 5828 | BasicBlock *NormalBB = getBasicBlock(ID: Record[OpNum++]); |
| 5829 | BasicBlock *UnwindBB = getBasicBlock(ID: Record[OpNum++]); |
| 5830 | |
| 5831 | unsigned FTyID = InvalidTypeID; |
| 5832 | FunctionType *FTy = nullptr; |
| 5833 | if ((CCInfo >> 13) & 1) { |
| 5834 | FTyID = Record[OpNum++]; |
| 5835 | FTy = dyn_cast<FunctionType>(Val: getTypeByID(ID: FTyID)); |
| 5836 | if (!FTy) |
| 5837 | return error(Message: "Explicit invoke type is not a function type" ); |
| 5838 | } |
| 5839 | |
| 5840 | Value *Callee; |
| 5841 | unsigned CalleeTypeID; |
| 5842 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Callee, TypeID&: CalleeTypeID, |
| 5843 | ConstExprInsertBB: CurBB)) |
| 5844 | return error(Message: "Invalid record" ); |
| 5845 | |
| 5846 | PointerType *CalleeTy = dyn_cast<PointerType>(Val: Callee->getType()); |
| 5847 | if (!CalleeTy) |
| 5848 | return error(Message: "Callee is not a pointer" ); |
| 5849 | if (!FTy) { |
| 5850 | FTyID = getContainedTypeID(ID: CalleeTypeID); |
| 5851 | FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID)); |
| 5852 | if (!FTy) |
| 5853 | return error(Message: "Callee is not of pointer to function type" ); |
| 5854 | } |
| 5855 | if (Record.size() < FTy->getNumParams() + OpNum) |
| 5856 | return error(Message: "Insufficient operands to call" ); |
| 5857 | |
| 5858 | SmallVector<Value*, 16> Ops; |
| 5859 | SmallVector<unsigned, 16> ArgTyIDs; |
| 5860 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { |
| 5861 | unsigned ArgTyID = getContainedTypeID(ID: FTyID, Idx: i + 1); |
| 5862 | Ops.push_back(Elt: getValue(Record, Slot: OpNum, InstNum: NextValueNo, Ty: FTy->getParamType(i), |
| 5863 | TyID: ArgTyID, ConstExprInsertBB: CurBB)); |
| 5864 | ArgTyIDs.push_back(Elt: ArgTyID); |
| 5865 | if (!Ops.back()) |
| 5866 | return error(Message: "Invalid record" ); |
| 5867 | } |
| 5868 | |
| 5869 | if (!FTy->isVarArg()) { |
| 5870 | if (Record.size() != OpNum) |
| 5871 | return error(Message: "Invalid record" ); |
| 5872 | } else { |
| 5873 | // Read type/value pairs for varargs params. |
| 5874 | while (OpNum != Record.size()) { |
| 5875 | Value *Op; |
| 5876 | unsigned OpTypeID; |
| 5877 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB)) |
| 5878 | return error(Message: "Invalid record" ); |
| 5879 | Ops.push_back(Elt: Op); |
| 5880 | ArgTyIDs.push_back(Elt: OpTypeID); |
| 5881 | } |
| 5882 | } |
| 5883 | |
| 5884 | // Upgrade the bundles if needed. |
| 5885 | if (!OperandBundles.empty()) |
| 5886 | UpgradeOperandBundles(OperandBundles); |
| 5887 | |
| 5888 | I = InvokeInst::Create(Ty: FTy, Func: Callee, IfNormal: NormalBB, IfException: UnwindBB, Args: Ops, |
| 5889 | Bundles: OperandBundles); |
| 5890 | ResTypeID = getContainedTypeID(ID: FTyID); |
| 5891 | OperandBundles.clear(); |
| 5892 | InstructionList.push_back(Elt: I); |
| 5893 | cast<InvokeInst>(Val: I)->setCallingConv( |
| 5894 | static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); |
| 5895 | cast<InvokeInst>(Val: I)->setAttributes(PAL); |
| 5896 | if (Error Err = propagateAttributeTypes(CB: cast<CallBase>(Val: I), ArgTyIDs)) { |
| 5897 | I->deleteValue(); |
| 5898 | return Err; |
| 5899 | } |
| 5900 | |
| 5901 | break; |
| 5902 | } |
| 5903 | case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] |
| 5904 | unsigned Idx = 0; |
| 5905 | Value *Val = nullptr; |
| 5906 | unsigned ValTypeID; |
| 5907 | if (getValueTypePair(Record, Slot&: Idx, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB)) |
| 5908 | return error(Message: "Invalid record" ); |
| 5909 | I = ResumeInst::Create(Exn: Val); |
| 5910 | InstructionList.push_back(Elt: I); |
| 5911 | break; |
| 5912 | } |
| 5913 | case bitc::FUNC_CODE_INST_CALLBR: { |
| 5914 | // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] |
| 5915 | unsigned OpNum = 0; |
| 5916 | AttributeList PAL = getAttributes(i: Record[OpNum++]); |
| 5917 | unsigned CCInfo = Record[OpNum++]; |
| 5918 | |
| 5919 | BasicBlock *DefaultDest = getBasicBlock(ID: Record[OpNum++]); |
| 5920 | unsigned NumIndirectDests = Record[OpNum++]; |
| 5921 | SmallVector<BasicBlock *, 16> IndirectDests; |
| 5922 | for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) |
| 5923 | IndirectDests.push_back(Elt: getBasicBlock(ID: Record[OpNum++])); |
| 5924 | |
| 5925 | unsigned FTyID = InvalidTypeID; |
| 5926 | FunctionType *FTy = nullptr; |
| 5927 | if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { |
| 5928 | FTyID = Record[OpNum++]; |
| 5929 | FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID)); |
| 5930 | if (!FTy) |
| 5931 | return error(Message: "Explicit call type is not a function type" ); |
| 5932 | } |
| 5933 | |
| 5934 | Value *Callee; |
| 5935 | unsigned CalleeTypeID; |
| 5936 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Callee, TypeID&: CalleeTypeID, |
| 5937 | ConstExprInsertBB: CurBB)) |
| 5938 | return error(Message: "Invalid record" ); |
| 5939 | |
| 5940 | PointerType *OpTy = dyn_cast<PointerType>(Val: Callee->getType()); |
| 5941 | if (!OpTy) |
| 5942 | return error(Message: "Callee is not a pointer type" ); |
| 5943 | if (!FTy) { |
| 5944 | FTyID = getContainedTypeID(ID: CalleeTypeID); |
| 5945 | FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID)); |
| 5946 | if (!FTy) |
| 5947 | return error(Message: "Callee is not of pointer to function type" ); |
| 5948 | } |
| 5949 | if (Record.size() < FTy->getNumParams() + OpNum) |
| 5950 | return error(Message: "Insufficient operands to call" ); |
| 5951 | |
| 5952 | SmallVector<Value*, 16> Args; |
| 5953 | SmallVector<unsigned, 16> ArgTyIDs; |
| 5954 | // Read the fixed params. |
| 5955 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { |
| 5956 | Value *Arg; |
| 5957 | unsigned ArgTyID = getContainedTypeID(ID: FTyID, Idx: i + 1); |
| 5958 | if (FTy->getParamType(i)->isLabelTy()) |
| 5959 | Arg = getBasicBlock(ID: Record[OpNum]); |
| 5960 | else |
| 5961 | Arg = getValue(Record, Slot: OpNum, InstNum: NextValueNo, Ty: FTy->getParamType(i), |
| 5962 | TyID: ArgTyID, ConstExprInsertBB: CurBB); |
| 5963 | if (!Arg) |
| 5964 | return error(Message: "Invalid record" ); |
| 5965 | Args.push_back(Elt: Arg); |
| 5966 | ArgTyIDs.push_back(Elt: ArgTyID); |
| 5967 | } |
| 5968 | |
| 5969 | // Read type/value pairs for varargs params. |
| 5970 | if (!FTy->isVarArg()) { |
| 5971 | if (OpNum != Record.size()) |
| 5972 | return error(Message: "Invalid record" ); |
| 5973 | } else { |
| 5974 | while (OpNum != Record.size()) { |
| 5975 | Value *Op; |
| 5976 | unsigned OpTypeID; |
| 5977 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB)) |
| 5978 | return error(Message: "Invalid record" ); |
| 5979 | Args.push_back(Elt: Op); |
| 5980 | ArgTyIDs.push_back(Elt: OpTypeID); |
| 5981 | } |
| 5982 | } |
| 5983 | |
| 5984 | // Upgrade the bundles if needed. |
| 5985 | if (!OperandBundles.empty()) |
| 5986 | UpgradeOperandBundles(OperandBundles); |
| 5987 | |
| 5988 | if (auto *IA = dyn_cast<InlineAsm>(Val: Callee)) { |
| 5989 | InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints(); |
| 5990 | auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) { |
| 5991 | return CI.Type == InlineAsm::isLabel; |
| 5992 | }; |
| 5993 | if (none_of(Range&: ConstraintInfo, P: IsLabelConstraint)) { |
| 5994 | // Upgrade explicit blockaddress arguments to label constraints. |
| 5995 | // Verify that the last arguments are blockaddress arguments that |
| 5996 | // match the indirect destinations. Clang always generates callbr |
| 5997 | // in this form. We could support reordering with more effort. |
| 5998 | unsigned FirstBlockArg = Args.size() - IndirectDests.size(); |
| 5999 | for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) { |
| 6000 | unsigned LabelNo = ArgNo - FirstBlockArg; |
| 6001 | auto *BA = dyn_cast<BlockAddress>(Val: Args[ArgNo]); |
| 6002 | if (!BA || BA->getFunction() != F || |
| 6003 | LabelNo > IndirectDests.size() || |
| 6004 | BA->getBasicBlock() != IndirectDests[LabelNo]) |
| 6005 | return error(Message: "callbr argument does not match indirect dest" ); |
| 6006 | } |
| 6007 | |
| 6008 | // Remove blockaddress arguments. |
| 6009 | Args.erase(CS: Args.begin() + FirstBlockArg, CE: Args.end()); |
| 6010 | ArgTyIDs.erase(CS: ArgTyIDs.begin() + FirstBlockArg, CE: ArgTyIDs.end()); |
| 6011 | |
| 6012 | // Recreate the function type with less arguments. |
| 6013 | SmallVector<Type *> ArgTys; |
| 6014 | for (Value *Arg : Args) |
| 6015 | ArgTys.push_back(Elt: Arg->getType()); |
| 6016 | FTy = |
| 6017 | FunctionType::get(Result: FTy->getReturnType(), Params: ArgTys, isVarArg: FTy->isVarArg()); |
| 6018 | |
| 6019 | // Update constraint string to use label constraints. |
| 6020 | std::string Constraints = IA->getConstraintString().str(); |
| 6021 | unsigned ArgNo = 0; |
| 6022 | size_t Pos = 0; |
| 6023 | for (const auto &CI : ConstraintInfo) { |
| 6024 | if (CI.hasArg()) { |
| 6025 | if (ArgNo >= FirstBlockArg) |
| 6026 | Constraints.insert(pos: Pos, s: "!" ); |
| 6027 | ++ArgNo; |
| 6028 | } |
| 6029 | |
| 6030 | // Go to next constraint in string. |
| 6031 | Pos = Constraints.find(c: ',', pos: Pos); |
| 6032 | if (Pos == std::string::npos) |
| 6033 | break; |
| 6034 | ++Pos; |
| 6035 | } |
| 6036 | |
| 6037 | Callee = InlineAsm::get(Ty: FTy, AsmString: IA->getAsmString(), Constraints, |
| 6038 | hasSideEffects: IA->hasSideEffects(), isAlignStack: IA->isAlignStack(), |
| 6039 | asmDialect: IA->getDialect(), canThrow: IA->canThrow()); |
| 6040 | } |
| 6041 | } |
| 6042 | |
| 6043 | I = CallBrInst::Create(Ty: FTy, Func: Callee, DefaultDest, IndirectDests, Args, |
| 6044 | Bundles: OperandBundles); |
| 6045 | ResTypeID = getContainedTypeID(ID: FTyID); |
| 6046 | OperandBundles.clear(); |
| 6047 | InstructionList.push_back(Elt: I); |
| 6048 | cast<CallBrInst>(Val: I)->setCallingConv( |
| 6049 | static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); |
| 6050 | cast<CallBrInst>(Val: I)->setAttributes(PAL); |
| 6051 | if (Error Err = propagateAttributeTypes(CB: cast<CallBase>(Val: I), ArgTyIDs)) { |
| 6052 | I->deleteValue(); |
| 6053 | return Err; |
| 6054 | } |
| 6055 | break; |
| 6056 | } |
| 6057 | case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE |
| 6058 | I = new UnreachableInst(Context); |
| 6059 | InstructionList.push_back(Elt: I); |
| 6060 | break; |
| 6061 | case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] |
| 6062 | if (Record.empty()) |
| 6063 | return error(Message: "Invalid phi record" ); |
| 6064 | // The first record specifies the type. |
| 6065 | unsigned TyID = Record[0]; |
| 6066 | Type *Ty = getTypeByID(ID: TyID); |
| 6067 | if (!Ty) |
| 6068 | return error(Message: "Invalid phi record" ); |
| 6069 | |
| 6070 | // Phi arguments are pairs of records of [value, basic block]. |
| 6071 | // There is an optional final record for fast-math-flags if this phi has a |
| 6072 | // floating-point type. |
| 6073 | size_t NumArgs = (Record.size() - 1) / 2; |
| 6074 | PHINode *PN = PHINode::Create(Ty, NumReservedValues: NumArgs); |
| 6075 | if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(Val: PN)) { |
| 6076 | PN->deleteValue(); |
| 6077 | return error(Message: "Invalid phi record" ); |
| 6078 | } |
| 6079 | InstructionList.push_back(Elt: PN); |
| 6080 | |
| 6081 | SmallDenseMap<BasicBlock *, Value *> Args; |
| 6082 | for (unsigned i = 0; i != NumArgs; i++) { |
| 6083 | BasicBlock *BB = getBasicBlock(ID: Record[i * 2 + 2]); |
| 6084 | if (!BB) { |
| 6085 | PN->deleteValue(); |
| 6086 | return error(Message: "Invalid phi BB" ); |
| 6087 | } |
| 6088 | |
| 6089 | // Phi nodes may contain the same predecessor multiple times, in which |
| 6090 | // case the incoming value must be identical. Directly reuse the already |
| 6091 | // seen value here, to avoid expanding a constant expression multiple |
| 6092 | // times. |
| 6093 | auto It = Args.find(Val: BB); |
| 6094 | BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup(Key: {BB, CurBB}); |
| 6095 | if (It != Args.end()) { |
| 6096 | // If this predecessor was also replaced with a constexpr basic |
| 6097 | // block, it must be de-duplicated. |
| 6098 | if (!EdgeBB) { |
| 6099 | PN->addIncoming(V: It->second, BB); |
| 6100 | } |
| 6101 | continue; |
| 6102 | } |
| 6103 | |
| 6104 | // If there already is a block for this edge (from a different phi), |
| 6105 | // use it. |
| 6106 | if (!EdgeBB) { |
| 6107 | // Otherwise, use a temporary block (that we will discard if it |
| 6108 | // turns out to be unnecessary). |
| 6109 | if (!PhiConstExprBB) |
| 6110 | PhiConstExprBB = BasicBlock::Create(Context, Name: "phi.constexpr" , Parent: F); |
| 6111 | EdgeBB = PhiConstExprBB; |
| 6112 | } |
| 6113 | |
| 6114 | // With the new function encoding, it is possible that operands have |
| 6115 | // negative IDs (for forward references). Use a signed VBR |
| 6116 | // representation to keep the encoding small. |
| 6117 | Value *V; |
| 6118 | if (UseRelativeIDs) |
| 6119 | V = getValueSigned(Record, Slot: i * 2 + 1, InstNum: NextValueNo, Ty, TyID, ConstExprInsertBB: EdgeBB); |
| 6120 | else |
| 6121 | V = getValue(Record, Slot: i * 2 + 1, InstNum: NextValueNo, Ty, TyID, ConstExprInsertBB: EdgeBB); |
| 6122 | if (!V) { |
| 6123 | PN->deleteValue(); |
| 6124 | PhiConstExprBB->eraseFromParent(); |
| 6125 | return error(Message: "Invalid phi record" ); |
| 6126 | } |
| 6127 | |
| 6128 | if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) { |
| 6129 | ConstExprEdgeBBs.insert(KV: {{BB, CurBB}, EdgeBB}); |
| 6130 | PhiConstExprBB = nullptr; |
| 6131 | } |
| 6132 | PN->addIncoming(V, BB); |
| 6133 | Args.insert(KV: {BB, V}); |
| 6134 | } |
| 6135 | I = PN; |
| 6136 | ResTypeID = TyID; |
| 6137 | |
| 6138 | // If there are an even number of records, the final record must be FMF. |
| 6139 | if (Record.size() % 2 == 0) { |
| 6140 | assert(isa<FPMathOperator>(I) && "Unexpected phi type" ); |
| 6141 | FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[Record.size() - 1]); |
| 6142 | if (FMF.any()) |
| 6143 | I->setFastMathFlags(FMF); |
| 6144 | } |
| 6145 | |
| 6146 | break; |
| 6147 | } |
| 6148 | |
| 6149 | case bitc::FUNC_CODE_INST_LANDINGPAD: |
| 6150 | case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { |
| 6151 | // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] |
| 6152 | unsigned Idx = 0; |
| 6153 | if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { |
| 6154 | if (Record.size() < 3) |
| 6155 | return error(Message: "Invalid record" ); |
| 6156 | } else { |
| 6157 | assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); |
| 6158 | if (Record.size() < 4) |
| 6159 | return error(Message: "Invalid record" ); |
| 6160 | } |
| 6161 | ResTypeID = Record[Idx++]; |
| 6162 | Type *Ty = getTypeByID(ID: ResTypeID); |
| 6163 | if (!Ty) |
| 6164 | return error(Message: "Invalid record" ); |
| 6165 | if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { |
| 6166 | Value *PersFn = nullptr; |
| 6167 | unsigned PersFnTypeID; |
| 6168 | if (getValueTypePair(Record, Slot&: Idx, InstNum: NextValueNo, ResVal&: PersFn, TypeID&: PersFnTypeID, |
| 6169 | ConstExprInsertBB: nullptr)) |
| 6170 | return error(Message: "Invalid record" ); |
| 6171 | |
| 6172 | if (!F->hasPersonalityFn()) |
| 6173 | F->setPersonalityFn(cast<Constant>(Val: PersFn)); |
| 6174 | else if (F->getPersonalityFn() != cast<Constant>(Val: PersFn)) |
| 6175 | return error(Message: "Personality function mismatch" ); |
| 6176 | } |
| 6177 | |
| 6178 | bool IsCleanup = !!Record[Idx++]; |
| 6179 | unsigned NumClauses = Record[Idx++]; |
| 6180 | LandingPadInst *LP = LandingPadInst::Create(RetTy: Ty, NumReservedClauses: NumClauses); |
| 6181 | LP->setCleanup(IsCleanup); |
| 6182 | for (unsigned J = 0; J != NumClauses; ++J) { |
| 6183 | LandingPadInst::ClauseType CT = |
| 6184 | LandingPadInst::ClauseType(Record[Idx++]); (void)CT; |
| 6185 | Value *Val; |
| 6186 | unsigned ValTypeID; |
| 6187 | |
| 6188 | if (getValueTypePair(Record, Slot&: Idx, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, |
| 6189 | ConstExprInsertBB: nullptr)) { |
| 6190 | delete LP; |
| 6191 | return error(Message: "Invalid record" ); |
| 6192 | } |
| 6193 | |
| 6194 | assert((CT != LandingPadInst::Catch || |
| 6195 | !isa<ArrayType>(Val->getType())) && |
| 6196 | "Catch clause has a invalid type!" ); |
| 6197 | assert((CT != LandingPadInst::Filter || |
| 6198 | isa<ArrayType>(Val->getType())) && |
| 6199 | "Filter clause has invalid type!" ); |
| 6200 | LP->addClause(ClauseVal: cast<Constant>(Val)); |
| 6201 | } |
| 6202 | |
| 6203 | I = LP; |
| 6204 | InstructionList.push_back(Elt: I); |
| 6205 | break; |
| 6206 | } |
| 6207 | |
| 6208 | case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] |
| 6209 | if (Record.size() != 4 && Record.size() != 5) |
| 6210 | return error(Message: "Invalid record" ); |
| 6211 | using APV = AllocaPackedValues; |
| 6212 | const uint64_t Rec = Record[3]; |
| 6213 | const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Packed: Rec); |
| 6214 | const bool SwiftError = Bitfield::get<APV::SwiftError>(Packed: Rec); |
| 6215 | unsigned TyID = Record[0]; |
| 6216 | Type *Ty = getTypeByID(ID: TyID); |
| 6217 | if (!Bitfield::get<APV::ExplicitType>(Packed: Rec)) { |
| 6218 | TyID = getContainedTypeID(ID: TyID); |
| 6219 | Ty = getTypeByID(ID: TyID); |
| 6220 | if (!Ty) |
| 6221 | return error(Message: "Missing element type for old-style alloca" ); |
| 6222 | } |
| 6223 | unsigned OpTyID = Record[1]; |
| 6224 | Type *OpTy = getTypeByID(ID: OpTyID); |
| 6225 | Value *Size = getFnValueByID(ID: Record[2], Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB); |
| 6226 | MaybeAlign Align; |
| 6227 | uint64_t AlignExp = |
| 6228 | Bitfield::get<APV::AlignLower>(Packed: Rec) | |
| 6229 | (Bitfield::get<APV::AlignUpper>(Packed: Rec) << APV::AlignLower::Bits); |
| 6230 | if (Error Err = parseAlignmentValue(Exponent: AlignExp, Alignment&: Align)) { |
| 6231 | return Err; |
| 6232 | } |
| 6233 | if (!Ty || !Size) |
| 6234 | return error(Message: "Invalid record" ); |
| 6235 | |
| 6236 | const DataLayout &DL = TheModule->getDataLayout(); |
| 6237 | unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace(); |
| 6238 | |
| 6239 | SmallPtrSet<Type *, 4> Visited; |
| 6240 | if (!Align && !Ty->isSized(Visited: &Visited)) |
| 6241 | return error(Message: "alloca of unsized type" ); |
| 6242 | if (!Align) |
| 6243 | Align = DL.getPrefTypeAlign(Ty); |
| 6244 | |
| 6245 | if (!Size->getType()->isIntegerTy()) |
| 6246 | return error(Message: "alloca element count must have integer type" ); |
| 6247 | |
| 6248 | AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); |
| 6249 | AI->setUsedWithInAlloca(InAlloca); |
| 6250 | AI->setSwiftError(SwiftError); |
| 6251 | I = AI; |
| 6252 | ResTypeID = getVirtualTypeID(Ty: AI->getType(), ChildTypeIDs: TyID); |
| 6253 | InstructionList.push_back(Elt: I); |
| 6254 | break; |
| 6255 | } |
| 6256 | case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] |
| 6257 | unsigned OpNum = 0; |
| 6258 | Value *Op; |
| 6259 | unsigned OpTypeID; |
| 6260 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB) || |
| 6261 | (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) |
| 6262 | return error(Message: "Invalid record" ); |
| 6263 | |
| 6264 | if (!isa<PointerType>(Val: Op->getType())) |
| 6265 | return error(Message: "Load operand is not a pointer type" ); |
| 6266 | |
| 6267 | Type *Ty = nullptr; |
| 6268 | if (OpNum + 3 == Record.size()) { |
| 6269 | ResTypeID = Record[OpNum++]; |
| 6270 | Ty = getTypeByID(ID: ResTypeID); |
| 6271 | } else { |
| 6272 | ResTypeID = getContainedTypeID(ID: OpTypeID); |
| 6273 | Ty = getTypeByID(ID: ResTypeID); |
| 6274 | } |
| 6275 | |
| 6276 | if (!Ty) |
| 6277 | return error(Message: "Missing load type" ); |
| 6278 | |
| 6279 | if (Error Err = typeCheckLoadStoreInst(ValType: Ty, PtrType: Op->getType())) |
| 6280 | return Err; |
| 6281 | |
| 6282 | MaybeAlign Align; |
| 6283 | if (Error Err = parseAlignmentValue(Exponent: Record[OpNum], Alignment&: Align)) |
| 6284 | return Err; |
| 6285 | SmallPtrSet<Type *, 4> Visited; |
| 6286 | if (!Align && !Ty->isSized(Visited: &Visited)) |
| 6287 | return error(Message: "load of unsized type" ); |
| 6288 | if (!Align) |
| 6289 | Align = TheModule->getDataLayout().getABITypeAlign(Ty); |
| 6290 | I = new LoadInst(Ty, Op, "" , Record[OpNum + 1], *Align); |
| 6291 | InstructionList.push_back(Elt: I); |
| 6292 | break; |
| 6293 | } |
| 6294 | case bitc::FUNC_CODE_INST_LOADATOMIC: { |
| 6295 | // LOADATOMIC: [opty, op, align, vol, ordering, ssid] |
| 6296 | unsigned OpNum = 0; |
| 6297 | Value *Op; |
| 6298 | unsigned OpTypeID; |
| 6299 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB) || |
| 6300 | (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) |
| 6301 | return error(Message: "Invalid record" ); |
| 6302 | |
| 6303 | if (!isa<PointerType>(Val: Op->getType())) |
| 6304 | return error(Message: "Load operand is not a pointer type" ); |
| 6305 | |
| 6306 | Type *Ty = nullptr; |
| 6307 | if (OpNum + 5 == Record.size()) { |
| 6308 | ResTypeID = Record[OpNum++]; |
| 6309 | Ty = getTypeByID(ID: ResTypeID); |
| 6310 | } else { |
| 6311 | ResTypeID = getContainedTypeID(ID: OpTypeID); |
| 6312 | Ty = getTypeByID(ID: ResTypeID); |
| 6313 | } |
| 6314 | |
| 6315 | if (!Ty) |
| 6316 | return error(Message: "Missing atomic load type" ); |
| 6317 | |
| 6318 | if (Error Err = typeCheckLoadStoreInst(ValType: Ty, PtrType: Op->getType())) |
| 6319 | return Err; |
| 6320 | |
| 6321 | AtomicOrdering Ordering = getDecodedOrdering(Val: Record[OpNum + 2]); |
| 6322 | if (Ordering == AtomicOrdering::NotAtomic || |
| 6323 | Ordering == AtomicOrdering::Release || |
| 6324 | Ordering == AtomicOrdering::AcquireRelease) |
| 6325 | return error(Message: "Invalid record" ); |
| 6326 | if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) |
| 6327 | return error(Message: "Invalid record" ); |
| 6328 | SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 3]); |
| 6329 | |
| 6330 | MaybeAlign Align; |
| 6331 | if (Error Err = parseAlignmentValue(Exponent: Record[OpNum], Alignment&: Align)) |
| 6332 | return Err; |
| 6333 | if (!Align) |
| 6334 | return error(Message: "Alignment missing from atomic load" ); |
| 6335 | I = new LoadInst(Ty, Op, "" , Record[OpNum + 1], *Align, Ordering, SSID); |
| 6336 | InstructionList.push_back(Elt: I); |
| 6337 | break; |
| 6338 | } |
| 6339 | case bitc::FUNC_CODE_INST_STORE: |
| 6340 | case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] |
| 6341 | unsigned OpNum = 0; |
| 6342 | Value *Val, *Ptr; |
| 6343 | unsigned PtrTypeID, ValTypeID; |
| 6344 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB)) |
| 6345 | return error(Message: "Invalid record" ); |
| 6346 | |
| 6347 | if (BitCode == bitc::FUNC_CODE_INST_STORE) { |
| 6348 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB)) |
| 6349 | return error(Message: "Invalid record" ); |
| 6350 | } else { |
| 6351 | ValTypeID = getContainedTypeID(ID: PtrTypeID); |
| 6352 | if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: getTypeByID(ID: ValTypeID), |
| 6353 | TyID: ValTypeID, ResVal&: Val, ConstExprInsertBB: CurBB)) |
| 6354 | return error(Message: "Invalid record" ); |
| 6355 | } |
| 6356 | |
| 6357 | if (OpNum + 2 != Record.size()) |
| 6358 | return error(Message: "Invalid record" ); |
| 6359 | |
| 6360 | if (Error Err = typeCheckLoadStoreInst(ValType: Val->getType(), PtrType: Ptr->getType())) |
| 6361 | return Err; |
| 6362 | MaybeAlign Align; |
| 6363 | if (Error Err = parseAlignmentValue(Exponent: Record[OpNum], Alignment&: Align)) |
| 6364 | return Err; |
| 6365 | SmallPtrSet<Type *, 4> Visited; |
| 6366 | if (!Align && !Val->getType()->isSized(Visited: &Visited)) |
| 6367 | return error(Message: "store of unsized type" ); |
| 6368 | if (!Align) |
| 6369 | Align = TheModule->getDataLayout().getABITypeAlign(Ty: Val->getType()); |
| 6370 | I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); |
| 6371 | InstructionList.push_back(Elt: I); |
| 6372 | break; |
| 6373 | } |
| 6374 | case bitc::FUNC_CODE_INST_STOREATOMIC: |
| 6375 | case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { |
| 6376 | // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] |
| 6377 | unsigned OpNum = 0; |
| 6378 | Value *Val, *Ptr; |
| 6379 | unsigned PtrTypeID, ValTypeID; |
| 6380 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB) || |
| 6381 | !isa<PointerType>(Val: Ptr->getType())) |
| 6382 | return error(Message: "Invalid record" ); |
| 6383 | if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) { |
| 6384 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB)) |
| 6385 | return error(Message: "Invalid record" ); |
| 6386 | } else { |
| 6387 | ValTypeID = getContainedTypeID(ID: PtrTypeID); |
| 6388 | if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: getTypeByID(ID: ValTypeID), |
| 6389 | TyID: ValTypeID, ResVal&: Val, ConstExprInsertBB: CurBB)) |
| 6390 | return error(Message: "Invalid record" ); |
| 6391 | } |
| 6392 | |
| 6393 | if (OpNum + 4 != Record.size()) |
| 6394 | return error(Message: "Invalid record" ); |
| 6395 | |
| 6396 | if (Error Err = typeCheckLoadStoreInst(ValType: Val->getType(), PtrType: Ptr->getType())) |
| 6397 | return Err; |
| 6398 | AtomicOrdering Ordering = getDecodedOrdering(Val: Record[OpNum + 2]); |
| 6399 | if (Ordering == AtomicOrdering::NotAtomic || |
| 6400 | Ordering == AtomicOrdering::Acquire || |
| 6401 | Ordering == AtomicOrdering::AcquireRelease) |
| 6402 | return error(Message: "Invalid record" ); |
| 6403 | SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 3]); |
| 6404 | if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) |
| 6405 | return error(Message: "Invalid record" ); |
| 6406 | |
| 6407 | MaybeAlign Align; |
| 6408 | if (Error Err = parseAlignmentValue(Exponent: Record[OpNum], Alignment&: Align)) |
| 6409 | return Err; |
| 6410 | if (!Align) |
| 6411 | return error(Message: "Alignment missing from atomic store" ); |
| 6412 | I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); |
| 6413 | InstructionList.push_back(Elt: I); |
| 6414 | break; |
| 6415 | } |
| 6416 | case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { |
| 6417 | // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, |
| 6418 | // failure_ordering?, weak?] |
| 6419 | const size_t NumRecords = Record.size(); |
| 6420 | unsigned OpNum = 0; |
| 6421 | Value *Ptr = nullptr; |
| 6422 | unsigned PtrTypeID; |
| 6423 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB)) |
| 6424 | return error(Message: "Invalid record" ); |
| 6425 | |
| 6426 | if (!isa<PointerType>(Val: Ptr->getType())) |
| 6427 | return error(Message: "Cmpxchg operand is not a pointer type" ); |
| 6428 | |
| 6429 | Value *Cmp = nullptr; |
| 6430 | unsigned CmpTypeID = getContainedTypeID(ID: PtrTypeID); |
| 6431 | if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: getTypeByID(ID: CmpTypeID), |
| 6432 | TyID: CmpTypeID, ResVal&: Cmp, ConstExprInsertBB: CurBB)) |
| 6433 | return error(Message: "Invalid record" ); |
| 6434 | |
| 6435 | Value *New = nullptr; |
| 6436 | if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: Cmp->getType(), TyID: CmpTypeID, |
| 6437 | ResVal&: New, ConstExprInsertBB: CurBB) || |
| 6438 | NumRecords < OpNum + 3 || NumRecords > OpNum + 5) |
| 6439 | return error(Message: "Invalid record" ); |
| 6440 | |
| 6441 | const AtomicOrdering SuccessOrdering = |
| 6442 | getDecodedOrdering(Val: Record[OpNum + 1]); |
| 6443 | if (SuccessOrdering == AtomicOrdering::NotAtomic || |
| 6444 | SuccessOrdering == AtomicOrdering::Unordered) |
| 6445 | return error(Message: "Invalid record" ); |
| 6446 | |
| 6447 | const SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 2]); |
| 6448 | |
| 6449 | if (Error Err = typeCheckLoadStoreInst(ValType: Cmp->getType(), PtrType: Ptr->getType())) |
| 6450 | return Err; |
| 6451 | |
| 6452 | const AtomicOrdering FailureOrdering = |
| 6453 | NumRecords < 7 |
| 6454 | ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) |
| 6455 | : getDecodedOrdering(Val: Record[OpNum + 3]); |
| 6456 | |
| 6457 | if (FailureOrdering == AtomicOrdering::NotAtomic || |
| 6458 | FailureOrdering == AtomicOrdering::Unordered) |
| 6459 | return error(Message: "Invalid record" ); |
| 6460 | |
| 6461 | const Align Alignment( |
| 6462 | TheModule->getDataLayout().getTypeStoreSize(Ty: Cmp->getType())); |
| 6463 | |
| 6464 | I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, |
| 6465 | FailureOrdering, SSID); |
| 6466 | cast<AtomicCmpXchgInst>(Val: I)->setVolatile(Record[OpNum]); |
| 6467 | |
| 6468 | if (NumRecords < 8) { |
| 6469 | // Before weak cmpxchgs existed, the instruction simply returned the |
| 6470 | // value loaded from memory, so bitcode files from that era will be |
| 6471 | // expecting the first component of a modern cmpxchg. |
| 6472 | I->insertInto(ParentBB: CurBB, It: CurBB->end()); |
| 6473 | I = ExtractValueInst::Create(Agg: I, Idxs: 0); |
| 6474 | ResTypeID = CmpTypeID; |
| 6475 | } else { |
| 6476 | cast<AtomicCmpXchgInst>(Val: I)->setWeak(Record[OpNum + 4]); |
| 6477 | unsigned I1TypeID = getVirtualTypeID(Ty: Type::getInt1Ty(C&: Context)); |
| 6478 | ResTypeID = getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: {CmpTypeID, I1TypeID}); |
| 6479 | } |
| 6480 | |
| 6481 | InstructionList.push_back(Elt: I); |
| 6482 | break; |
| 6483 | } |
| 6484 | case bitc::FUNC_CODE_INST_CMPXCHG: { |
| 6485 | // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, |
| 6486 | // failure_ordering, weak, align?] |
| 6487 | const size_t NumRecords = Record.size(); |
| 6488 | unsigned OpNum = 0; |
| 6489 | Value *Ptr = nullptr; |
| 6490 | unsigned PtrTypeID; |
| 6491 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB)) |
| 6492 | return error(Message: "Invalid record" ); |
| 6493 | |
| 6494 | if (!isa<PointerType>(Val: Ptr->getType())) |
| 6495 | return error(Message: "Cmpxchg operand is not a pointer type" ); |
| 6496 | |
| 6497 | Value *Cmp = nullptr; |
| 6498 | unsigned CmpTypeID; |
| 6499 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Cmp, TypeID&: CmpTypeID, ConstExprInsertBB: CurBB)) |
| 6500 | return error(Message: "Invalid record" ); |
| 6501 | |
| 6502 | Value *Val = nullptr; |
| 6503 | if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: Cmp->getType(), TyID: CmpTypeID, ResVal&: Val, |
| 6504 | ConstExprInsertBB: CurBB)) |
| 6505 | return error(Message: "Invalid record" ); |
| 6506 | |
| 6507 | if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) |
| 6508 | return error(Message: "Invalid record" ); |
| 6509 | |
| 6510 | const bool IsVol = Record[OpNum]; |
| 6511 | |
| 6512 | const AtomicOrdering SuccessOrdering = |
| 6513 | getDecodedOrdering(Val: Record[OpNum + 1]); |
| 6514 | if (!AtomicCmpXchgInst::isValidSuccessOrdering(Ordering: SuccessOrdering)) |
| 6515 | return error(Message: "Invalid cmpxchg success ordering" ); |
| 6516 | |
| 6517 | const SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 2]); |
| 6518 | |
| 6519 | if (Error Err = typeCheckLoadStoreInst(ValType: Cmp->getType(), PtrType: Ptr->getType())) |
| 6520 | return Err; |
| 6521 | |
| 6522 | const AtomicOrdering FailureOrdering = |
| 6523 | getDecodedOrdering(Val: Record[OpNum + 3]); |
| 6524 | if (!AtomicCmpXchgInst::isValidFailureOrdering(Ordering: FailureOrdering)) |
| 6525 | return error(Message: "Invalid cmpxchg failure ordering" ); |
| 6526 | |
| 6527 | const bool IsWeak = Record[OpNum + 4]; |
| 6528 | |
| 6529 | MaybeAlign Alignment; |
| 6530 | |
| 6531 | if (NumRecords == (OpNum + 6)) { |
| 6532 | if (Error Err = parseAlignmentValue(Exponent: Record[OpNum + 5], Alignment)) |
| 6533 | return Err; |
| 6534 | } |
| 6535 | if (!Alignment) |
| 6536 | Alignment = |
| 6537 | Align(TheModule->getDataLayout().getTypeStoreSize(Ty: Cmp->getType())); |
| 6538 | |
| 6539 | I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, |
| 6540 | FailureOrdering, SSID); |
| 6541 | cast<AtomicCmpXchgInst>(Val: I)->setVolatile(IsVol); |
| 6542 | cast<AtomicCmpXchgInst>(Val: I)->setWeak(IsWeak); |
| 6543 | |
| 6544 | unsigned I1TypeID = getVirtualTypeID(Ty: Type::getInt1Ty(C&: Context)); |
| 6545 | ResTypeID = getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: {CmpTypeID, I1TypeID}); |
| 6546 | |
| 6547 | InstructionList.push_back(Elt: I); |
| 6548 | break; |
| 6549 | } |
| 6550 | case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: |
| 6551 | case bitc::FUNC_CODE_INST_ATOMICRMW: { |
| 6552 | // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] |
| 6553 | // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] |
| 6554 | const size_t NumRecords = Record.size(); |
| 6555 | unsigned OpNum = 0; |
| 6556 | |
| 6557 | Value *Ptr = nullptr; |
| 6558 | unsigned PtrTypeID; |
| 6559 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB)) |
| 6560 | return error(Message: "Invalid record" ); |
| 6561 | |
| 6562 | if (!isa<PointerType>(Val: Ptr->getType())) |
| 6563 | return error(Message: "Invalid record" ); |
| 6564 | |
| 6565 | Value *Val = nullptr; |
| 6566 | unsigned ValTypeID = InvalidTypeID; |
| 6567 | if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { |
| 6568 | ValTypeID = getContainedTypeID(ID: PtrTypeID); |
| 6569 | if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, |
| 6570 | Ty: getTypeByID(ID: ValTypeID), TyID: ValTypeID, ResVal&: Val, ConstExprInsertBB: CurBB)) |
| 6571 | return error(Message: "Invalid record" ); |
| 6572 | } else { |
| 6573 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB)) |
| 6574 | return error(Message: "Invalid record" ); |
| 6575 | } |
| 6576 | |
| 6577 | if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) |
| 6578 | return error(Message: "Invalid record" ); |
| 6579 | |
| 6580 | const AtomicRMWInst::BinOp Operation = |
| 6581 | getDecodedRMWOperation(Val: Record[OpNum]); |
| 6582 | if (Operation < AtomicRMWInst::FIRST_BINOP || |
| 6583 | Operation > AtomicRMWInst::LAST_BINOP) |
| 6584 | return error(Message: "Invalid record" ); |
| 6585 | |
| 6586 | const bool IsVol = Record[OpNum + 1]; |
| 6587 | |
| 6588 | const AtomicOrdering Ordering = getDecodedOrdering(Val: Record[OpNum + 2]); |
| 6589 | if (Ordering == AtomicOrdering::NotAtomic || |
| 6590 | Ordering == AtomicOrdering::Unordered) |
| 6591 | return error(Message: "Invalid record" ); |
| 6592 | |
| 6593 | const SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 3]); |
| 6594 | |
| 6595 | MaybeAlign Alignment; |
| 6596 | |
| 6597 | if (NumRecords == (OpNum + 5)) { |
| 6598 | if (Error Err = parseAlignmentValue(Exponent: Record[OpNum + 4], Alignment)) |
| 6599 | return Err; |
| 6600 | } |
| 6601 | |
| 6602 | if (!Alignment) |
| 6603 | Alignment = |
| 6604 | Align(TheModule->getDataLayout().getTypeStoreSize(Ty: Val->getType())); |
| 6605 | |
| 6606 | I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); |
| 6607 | ResTypeID = ValTypeID; |
| 6608 | cast<AtomicRMWInst>(Val: I)->setVolatile(IsVol); |
| 6609 | |
| 6610 | InstructionList.push_back(Elt: I); |
| 6611 | break; |
| 6612 | } |
| 6613 | case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] |
| 6614 | if (2 != Record.size()) |
| 6615 | return error(Message: "Invalid record" ); |
| 6616 | AtomicOrdering Ordering = getDecodedOrdering(Val: Record[0]); |
| 6617 | if (Ordering == AtomicOrdering::NotAtomic || |
| 6618 | Ordering == AtomicOrdering::Unordered || |
| 6619 | Ordering == AtomicOrdering::Monotonic) |
| 6620 | return error(Message: "Invalid record" ); |
| 6621 | SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[1]); |
| 6622 | I = new FenceInst(Context, Ordering, SSID); |
| 6623 | InstructionList.push_back(Elt: I); |
| 6624 | break; |
| 6625 | } |
| 6626 | case bitc::FUNC_CODE_DEBUG_RECORD_LABEL: { |
| 6627 | // DbgLabelRecords are placed after the Instructions that they are |
| 6628 | // attached to. |
| 6629 | SeenDebugRecord = true; |
| 6630 | Instruction *Inst = getLastInstruction(); |
| 6631 | if (!Inst) |
| 6632 | return error(Message: "Invalid dbg record: missing instruction" ); |
| 6633 | DILocation *DIL = cast<DILocation>(Val: getFnMetadataByID(ID: Record[0])); |
| 6634 | DILabel *Label = cast<DILabel>(Val: getFnMetadataByID(ID: Record[1])); |
| 6635 | Inst->getParent()->insertDbgRecordBefore( |
| 6636 | DR: new DbgLabelRecord(Label, DebugLoc(DIL)), Here: Inst->getIterator()); |
| 6637 | continue; // This isn't an instruction. |
| 6638 | } |
| 6639 | case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE: |
| 6640 | case bitc::FUNC_CODE_DEBUG_RECORD_VALUE: |
| 6641 | case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE: |
| 6642 | case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: { |
| 6643 | // DbgVariableRecords are placed after the Instructions that they are |
| 6644 | // attached to. |
| 6645 | SeenDebugRecord = true; |
| 6646 | Instruction *Inst = getLastInstruction(); |
| 6647 | if (!Inst) |
| 6648 | return error(Message: "Invalid dbg record: missing instruction" ); |
| 6649 | |
| 6650 | // First 3 fields are common to all kinds: |
| 6651 | // DILocation, DILocalVariable, DIExpression |
| 6652 | // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE) |
| 6653 | // ..., LocationMetadata |
| 6654 | // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd) |
| 6655 | // ..., Value |
| 6656 | // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE) |
| 6657 | // ..., LocationMetadata |
| 6658 | // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN) |
| 6659 | // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata |
| 6660 | unsigned Slot = 0; |
| 6661 | // Common fields (0-2). |
| 6662 | DILocation *DIL = cast<DILocation>(Val: getFnMetadataByID(ID: Record[Slot++])); |
| 6663 | DILocalVariable *Var = |
| 6664 | cast<DILocalVariable>(Val: getFnMetadataByID(ID: Record[Slot++])); |
| 6665 | DIExpression *Expr = |
| 6666 | cast<DIExpression>(Val: getFnMetadataByID(ID: Record[Slot++])); |
| 6667 | |
| 6668 | // Union field (3: LocationMetadata | Value). |
| 6669 | Metadata *RawLocation = nullptr; |
| 6670 | if (BitCode == bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE) { |
| 6671 | Value *V = nullptr; |
| 6672 | unsigned TyID = 0; |
| 6673 | // We never expect to see a fwd reference value here because |
| 6674 | // use-before-defs are encoded with the standard non-abbrev record |
| 6675 | // type (they'd require encoding the type too, and they're rare). As a |
| 6676 | // result, getValueTypePair only ever increments Slot by one here (once |
| 6677 | // for the value, never twice for value and type). |
| 6678 | unsigned SlotBefore = Slot; |
| 6679 | if (getValueTypePair(Record, Slot, InstNum: NextValueNo, ResVal&: V, TypeID&: TyID, ConstExprInsertBB: CurBB)) |
| 6680 | return error(Message: "Invalid dbg record: invalid value" ); |
| 6681 | (void)SlotBefore; |
| 6682 | assert((SlotBefore == Slot - 1) && "unexpected fwd ref" ); |
| 6683 | RawLocation = ValueAsMetadata::get(V); |
| 6684 | } else { |
| 6685 | RawLocation = getFnMetadataByID(ID: Record[Slot++]); |
| 6686 | } |
| 6687 | |
| 6688 | DbgVariableRecord *DVR = nullptr; |
| 6689 | switch (BitCode) { |
| 6690 | case bitc::FUNC_CODE_DEBUG_RECORD_VALUE: |
| 6691 | case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE: |
| 6692 | DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL, |
| 6693 | DbgVariableRecord::LocationType::Value); |
| 6694 | break; |
| 6695 | case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE: |
| 6696 | DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL, |
| 6697 | DbgVariableRecord::LocationType::Declare); |
| 6698 | break; |
| 6699 | case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: { |
| 6700 | DIAssignID *ID = cast<DIAssignID>(Val: getFnMetadataByID(ID: Record[Slot++])); |
| 6701 | DIExpression *AddrExpr = |
| 6702 | cast<DIExpression>(Val: getFnMetadataByID(ID: Record[Slot++])); |
| 6703 | Metadata *Addr = getFnMetadataByID(ID: Record[Slot++]); |
| 6704 | DVR = new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr, |
| 6705 | DIL); |
| 6706 | break; |
| 6707 | } |
| 6708 | default: |
| 6709 | llvm_unreachable("Unknown DbgVariableRecord bitcode" ); |
| 6710 | } |
| 6711 | Inst->getParent()->insertDbgRecordBefore(DR: DVR, Here: Inst->getIterator()); |
| 6712 | continue; // This isn't an instruction. |
| 6713 | } |
| 6714 | case bitc::FUNC_CODE_INST_CALL: { |
| 6715 | // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] |
| 6716 | if (Record.size() < 3) |
| 6717 | return error(Message: "Invalid record" ); |
| 6718 | |
| 6719 | unsigned OpNum = 0; |
| 6720 | AttributeList PAL = getAttributes(i: Record[OpNum++]); |
| 6721 | unsigned CCInfo = Record[OpNum++]; |
| 6722 | |
| 6723 | FastMathFlags FMF; |
| 6724 | if ((CCInfo >> bitc::CALL_FMF) & 1) { |
| 6725 | FMF = getDecodedFastMathFlags(Val: Record[OpNum++]); |
| 6726 | if (!FMF.any()) |
| 6727 | return error(Message: "Fast math flags indicator set for call with no FMF" ); |
| 6728 | } |
| 6729 | |
| 6730 | unsigned FTyID = InvalidTypeID; |
| 6731 | FunctionType *FTy = nullptr; |
| 6732 | if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { |
| 6733 | FTyID = Record[OpNum++]; |
| 6734 | FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID)); |
| 6735 | if (!FTy) |
| 6736 | return error(Message: "Explicit call type is not a function type" ); |
| 6737 | } |
| 6738 | |
| 6739 | Value *Callee; |
| 6740 | unsigned CalleeTypeID; |
| 6741 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Callee, TypeID&: CalleeTypeID, |
| 6742 | ConstExprInsertBB: CurBB)) |
| 6743 | return error(Message: "Invalid record" ); |
| 6744 | |
| 6745 | PointerType *OpTy = dyn_cast<PointerType>(Val: Callee->getType()); |
| 6746 | if (!OpTy) |
| 6747 | return error(Message: "Callee is not a pointer type" ); |
| 6748 | if (!FTy) { |
| 6749 | FTyID = getContainedTypeID(ID: CalleeTypeID); |
| 6750 | FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID)); |
| 6751 | if (!FTy) |
| 6752 | return error(Message: "Callee is not of pointer to function type" ); |
| 6753 | } |
| 6754 | if (Record.size() < FTy->getNumParams() + OpNum) |
| 6755 | return error(Message: "Insufficient operands to call" ); |
| 6756 | |
| 6757 | SmallVector<Value*, 16> Args; |
| 6758 | SmallVector<unsigned, 16> ArgTyIDs; |
| 6759 | // Read the fixed params. |
| 6760 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { |
| 6761 | unsigned ArgTyID = getContainedTypeID(ID: FTyID, Idx: i + 1); |
| 6762 | if (FTy->getParamType(i)->isLabelTy()) |
| 6763 | Args.push_back(Elt: getBasicBlock(ID: Record[OpNum])); |
| 6764 | else |
| 6765 | Args.push_back(Elt: getValue(Record, Slot: OpNum, InstNum: NextValueNo, |
| 6766 | Ty: FTy->getParamType(i), TyID: ArgTyID, ConstExprInsertBB: CurBB)); |
| 6767 | ArgTyIDs.push_back(Elt: ArgTyID); |
| 6768 | if (!Args.back()) |
| 6769 | return error(Message: "Invalid record" ); |
| 6770 | } |
| 6771 | |
| 6772 | // Read type/value pairs for varargs params. |
| 6773 | if (!FTy->isVarArg()) { |
| 6774 | if (OpNum != Record.size()) |
| 6775 | return error(Message: "Invalid record" ); |
| 6776 | } else { |
| 6777 | while (OpNum != Record.size()) { |
| 6778 | Value *Op; |
| 6779 | unsigned OpTypeID; |
| 6780 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB)) |
| 6781 | return error(Message: "Invalid record" ); |
| 6782 | Args.push_back(Elt: Op); |
| 6783 | ArgTyIDs.push_back(Elt: OpTypeID); |
| 6784 | } |
| 6785 | } |
| 6786 | |
| 6787 | // Upgrade the bundles if needed. |
| 6788 | if (!OperandBundles.empty()) |
| 6789 | UpgradeOperandBundles(OperandBundles); |
| 6790 | |
| 6791 | I = CallInst::Create(Ty: FTy, Func: Callee, Args, Bundles: OperandBundles); |
| 6792 | ResTypeID = getContainedTypeID(ID: FTyID); |
| 6793 | OperandBundles.clear(); |
| 6794 | InstructionList.push_back(Elt: I); |
| 6795 | cast<CallInst>(Val: I)->setCallingConv( |
| 6796 | static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); |
| 6797 | CallInst::TailCallKind TCK = CallInst::TCK_None; |
| 6798 | if (CCInfo & (1 << bitc::CALL_TAIL)) |
| 6799 | TCK = CallInst::TCK_Tail; |
| 6800 | if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) |
| 6801 | TCK = CallInst::TCK_MustTail; |
| 6802 | if (CCInfo & (1 << bitc::CALL_NOTAIL)) |
| 6803 | TCK = CallInst::TCK_NoTail; |
| 6804 | cast<CallInst>(Val: I)->setTailCallKind(TCK); |
| 6805 | cast<CallInst>(Val: I)->setAttributes(PAL); |
| 6806 | if (isa<DbgInfoIntrinsic>(Val: I)) |
| 6807 | SeenDebugIntrinsic = true; |
| 6808 | if (Error Err = propagateAttributeTypes(CB: cast<CallBase>(Val: I), ArgTyIDs)) { |
| 6809 | I->deleteValue(); |
| 6810 | return Err; |
| 6811 | } |
| 6812 | if (FMF.any()) { |
| 6813 | if (!isa<FPMathOperator>(Val: I)) |
| 6814 | return error(Message: "Fast-math-flags specified for call without " |
| 6815 | "floating-point scalar or vector return type" ); |
| 6816 | I->setFastMathFlags(FMF); |
| 6817 | } |
| 6818 | break; |
| 6819 | } |
| 6820 | case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] |
| 6821 | if (Record.size() < 3) |
| 6822 | return error(Message: "Invalid record" ); |
| 6823 | unsigned OpTyID = Record[0]; |
| 6824 | Type *OpTy = getTypeByID(ID: OpTyID); |
| 6825 | Value *Op = getValue(Record, Slot: 1, InstNum: NextValueNo, Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB); |
| 6826 | ResTypeID = Record[2]; |
| 6827 | Type *ResTy = getTypeByID(ID: ResTypeID); |
| 6828 | if (!OpTy || !Op || !ResTy) |
| 6829 | return error(Message: "Invalid record" ); |
| 6830 | I = new VAArgInst(Op, ResTy); |
| 6831 | InstructionList.push_back(Elt: I); |
| 6832 | break; |
| 6833 | } |
| 6834 | |
| 6835 | case bitc::FUNC_CODE_OPERAND_BUNDLE: { |
| 6836 | // A call or an invoke can be optionally prefixed with some variable |
| 6837 | // number of operand bundle blocks. These blocks are read into |
| 6838 | // OperandBundles and consumed at the next call or invoke instruction. |
| 6839 | |
| 6840 | if (Record.empty() || Record[0] >= BundleTags.size()) |
| 6841 | return error(Message: "Invalid record" ); |
| 6842 | |
| 6843 | std::vector<Value *> Inputs; |
| 6844 | |
| 6845 | unsigned OpNum = 1; |
| 6846 | while (OpNum != Record.size()) { |
| 6847 | Value *Op; |
| 6848 | if (getValueOrMetadata(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, ConstExprInsertBB: CurBB)) |
| 6849 | return error(Message: "Invalid record" ); |
| 6850 | Inputs.push_back(x: Op); |
| 6851 | } |
| 6852 | |
| 6853 | OperandBundles.emplace_back(args&: BundleTags[Record[0]], args: std::move(Inputs)); |
| 6854 | continue; |
| 6855 | } |
| 6856 | |
| 6857 | case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] |
| 6858 | unsigned OpNum = 0; |
| 6859 | Value *Op = nullptr; |
| 6860 | unsigned OpTypeID; |
| 6861 | if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB)) |
| 6862 | return error(Message: "Invalid record" ); |
| 6863 | if (OpNum != Record.size()) |
| 6864 | return error(Message: "Invalid record" ); |
| 6865 | |
| 6866 | I = new FreezeInst(Op); |
| 6867 | ResTypeID = OpTypeID; |
| 6868 | InstructionList.push_back(Elt: I); |
| 6869 | break; |
| 6870 | } |
| 6871 | } |
| 6872 | |
| 6873 | // Add instruction to end of current BB. If there is no current BB, reject |
| 6874 | // this file. |
| 6875 | if (!CurBB) { |
| 6876 | I->deleteValue(); |
| 6877 | return error(Message: "Invalid instruction with no BB" ); |
| 6878 | } |
| 6879 | if (!OperandBundles.empty()) { |
| 6880 | I->deleteValue(); |
| 6881 | return error(Message: "Operand bundles found with no consumer" ); |
| 6882 | } |
| 6883 | I->insertInto(ParentBB: CurBB, It: CurBB->end()); |
| 6884 | |
| 6885 | // If this was a terminator instruction, move to the next block. |
| 6886 | if (I->isTerminator()) { |
| 6887 | ++CurBBNo; |
| 6888 | CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; |
| 6889 | } |
| 6890 | |
| 6891 | // Non-void values get registered in the value table for future use. |
| 6892 | if (!I->getType()->isVoidTy()) { |
| 6893 | assert(I->getType() == getTypeByID(ResTypeID) && |
| 6894 | "Incorrect result type ID" ); |
| 6895 | if (Error Err = ValueList.assignValue(Idx: NextValueNo++, V: I, TypeID: ResTypeID)) |
| 6896 | return Err; |
| 6897 | } |
| 6898 | } |
| 6899 | |
| 6900 | OutOfRecordLoop: |
| 6901 | |
| 6902 | if (!OperandBundles.empty()) |
| 6903 | return error(Message: "Operand bundles found with no consumer" ); |
| 6904 | |
| 6905 | // Check the function list for unresolved values. |
| 6906 | if (Argument *A = dyn_cast<Argument>(Val: ValueList.back())) { |
| 6907 | if (!A->getParent()) { |
| 6908 | // We found at least one unresolved value. Nuke them all to avoid leaks. |
| 6909 | for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ |
| 6910 | if ((A = dyn_cast_or_null<Argument>(Val: ValueList[i])) && !A->getParent()) { |
| 6911 | A->replaceAllUsesWith(V: PoisonValue::get(T: A->getType())); |
| 6912 | delete A; |
| 6913 | } |
| 6914 | } |
| 6915 | return error(Message: "Never resolved value found in function" ); |
| 6916 | } |
| 6917 | } |
| 6918 | |
| 6919 | // Unexpected unresolved metadata about to be dropped. |
| 6920 | if (MDLoader->hasFwdRefs()) |
| 6921 | return error(Message: "Invalid function metadata: outgoing forward refs" ); |
| 6922 | |
| 6923 | if (PhiConstExprBB) |
| 6924 | PhiConstExprBB->eraseFromParent(); |
| 6925 | |
| 6926 | for (const auto &Pair : ConstExprEdgeBBs) { |
| 6927 | BasicBlock *From = Pair.first.first; |
| 6928 | BasicBlock *To = Pair.first.second; |
| 6929 | BasicBlock *EdgeBB = Pair.second; |
| 6930 | BranchInst::Create(IfTrue: To, InsertBefore: EdgeBB); |
| 6931 | From->getTerminator()->replaceSuccessorWith(OldBB: To, NewBB: EdgeBB); |
| 6932 | To->replacePhiUsesWith(Old: From, New: EdgeBB); |
| 6933 | EdgeBB->moveBefore(MovePos: To); |
| 6934 | } |
| 6935 | |
| 6936 | // Trim the value list down to the size it was before we parsed this function. |
| 6937 | ValueList.shrinkTo(N: ModuleValueListSize); |
| 6938 | MDLoader->shrinkTo(N: ModuleMDLoaderSize); |
| 6939 | std::vector<BasicBlock*>().swap(x&: FunctionBBs); |
| 6940 | return Error::success(); |
| 6941 | } |
| 6942 | |
| 6943 | /// Find the function body in the bitcode stream |
| 6944 | Error BitcodeReader::findFunctionInStream( |
| 6945 | Function *F, |
| 6946 | DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { |
| 6947 | while (DeferredFunctionInfoIterator->second == 0) { |
| 6948 | // This is the fallback handling for the old format bitcode that |
| 6949 | // didn't contain the function index in the VST, or when we have |
| 6950 | // an anonymous function which would not have a VST entry. |
| 6951 | // Assert that we have one of those two cases. |
| 6952 | assert(VSTOffset == 0 || !F->hasName()); |
| 6953 | // Parse the next body in the stream and set its position in the |
| 6954 | // DeferredFunctionInfo map. |
| 6955 | if (Error Err = rememberAndSkipFunctionBodies()) |
| 6956 | return Err; |
| 6957 | } |
| 6958 | return Error::success(); |
| 6959 | } |
| 6960 | |
| 6961 | SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { |
| 6962 | if (Val == SyncScope::SingleThread || Val == SyncScope::System) |
| 6963 | return SyncScope::ID(Val); |
| 6964 | if (Val >= SSIDs.size()) |
| 6965 | return SyncScope::System; // Map unknown synchronization scopes to system. |
| 6966 | return SSIDs[Val]; |
| 6967 | } |
| 6968 | |
| 6969 | //===----------------------------------------------------------------------===// |
| 6970 | // GVMaterializer implementation |
| 6971 | //===----------------------------------------------------------------------===// |
| 6972 | |
| 6973 | Error BitcodeReader::materialize(GlobalValue *GV) { |
| 6974 | Function *F = dyn_cast<Function>(Val: GV); |
| 6975 | // If it's not a function or is already material, ignore the request. |
| 6976 | if (!F || !F->isMaterializable()) |
| 6977 | return Error::success(); |
| 6978 | |
| 6979 | DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(Val: F); |
| 6980 | assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!" ); |
| 6981 | // If its position is recorded as 0, its body is somewhere in the stream |
| 6982 | // but we haven't seen it yet. |
| 6983 | if (DFII->second == 0) |
| 6984 | if (Error Err = findFunctionInStream(F, DeferredFunctionInfoIterator: DFII)) |
| 6985 | return Err; |
| 6986 | |
| 6987 | // Materialize metadata before parsing any function bodies. |
| 6988 | if (Error Err = materializeMetadata()) |
| 6989 | return Err; |
| 6990 | |
| 6991 | // Move the bit stream to the saved position of the deferred function body. |
| 6992 | if (Error JumpFailed = Stream.JumpToBit(BitNo: DFII->second)) |
| 6993 | return JumpFailed; |
| 6994 | |
| 6995 | if (Error Err = parseFunctionBody(F)) |
| 6996 | return Err; |
| 6997 | F->setIsMaterializable(false); |
| 6998 | |
| 6999 | // All parsed Functions should load into the debug info format dictated by the |
| 7000 | // Module. |
| 7001 | if (SeenDebugIntrinsic && SeenDebugRecord) |
| 7002 | return error(Message: "Mixed debug intrinsics and debug records in bitcode module!" ); |
| 7003 | |
| 7004 | if (StripDebugInfo) |
| 7005 | stripDebugInfo(F&: *F); |
| 7006 | |
| 7007 | // Upgrade any old intrinsic calls in the function. |
| 7008 | for (auto &I : UpgradedIntrinsics) { |
| 7009 | for (User *U : llvm::make_early_inc_range(Range: I.first->materialized_users())) |
| 7010 | if (CallInst *CI = dyn_cast<CallInst>(Val: U)) |
| 7011 | UpgradeIntrinsicCall(CB: CI, NewFn: I.second); |
| 7012 | } |
| 7013 | |
| 7014 | // Finish fn->subprogram upgrade for materialized functions. |
| 7015 | if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) |
| 7016 | F->setSubprogram(SP); |
| 7017 | |
| 7018 | // Check if the TBAA Metadata are valid, otherwise we will need to strip them. |
| 7019 | if (!MDLoader->isStrippingTBAA()) { |
| 7020 | for (auto &I : instructions(F)) { |
| 7021 | MDNode *TBAA = I.getMetadata(KindID: LLVMContext::MD_tbaa); |
| 7022 | if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, MD: TBAA)) |
| 7023 | continue; |
| 7024 | MDLoader->setStripTBAA(true); |
| 7025 | stripTBAA(M: F->getParent()); |
| 7026 | } |
| 7027 | } |
| 7028 | |
| 7029 | for (auto &I : instructions(F)) { |
| 7030 | // "Upgrade" older incorrect branch weights by dropping them. |
| 7031 | if (auto *MD = I.getMetadata(KindID: LLVMContext::MD_prof)) { |
| 7032 | if (MD->getOperand(I: 0) != nullptr && isa<MDString>(Val: MD->getOperand(I: 0))) { |
| 7033 | MDString *MDS = cast<MDString>(Val: MD->getOperand(I: 0)); |
| 7034 | StringRef ProfName = MDS->getString(); |
| 7035 | // Check consistency of !prof branch_weights metadata. |
| 7036 | if (ProfName != MDProfLabels::BranchWeights) |
| 7037 | continue; |
| 7038 | unsigned ExpectedNumOperands = 0; |
| 7039 | if (BranchInst *BI = dyn_cast<BranchInst>(Val: &I)) |
| 7040 | ExpectedNumOperands = BI->getNumSuccessors(); |
| 7041 | else if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: &I)) |
| 7042 | ExpectedNumOperands = SI->getNumSuccessors(); |
| 7043 | else if (isa<CallInst>(Val: &I)) |
| 7044 | ExpectedNumOperands = 1; |
| 7045 | else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(Val: &I)) |
| 7046 | ExpectedNumOperands = IBI->getNumDestinations(); |
| 7047 | else if (isa<SelectInst>(Val: &I)) |
| 7048 | ExpectedNumOperands = 2; |
| 7049 | else |
| 7050 | continue; // ignore and continue. |
| 7051 | |
| 7052 | unsigned Offset = getBranchWeightOffset(ProfileData: MD); |
| 7053 | |
| 7054 | // If branch weight doesn't match, just strip branch weight. |
| 7055 | if (MD->getNumOperands() != Offset + ExpectedNumOperands) |
| 7056 | I.setMetadata(KindID: LLVMContext::MD_prof, Node: nullptr); |
| 7057 | } |
| 7058 | } |
| 7059 | |
| 7060 | // Remove incompatible attributes on function calls. |
| 7061 | if (auto *CI = dyn_cast<CallBase>(Val: &I)) { |
| 7062 | CI->removeRetAttrs(AttrsToRemove: AttributeFuncs::typeIncompatible( |
| 7063 | Ty: CI->getFunctionType()->getReturnType(), AS: CI->getRetAttributes())); |
| 7064 | |
| 7065 | for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) |
| 7066 | CI->removeParamAttrs(ArgNo, AttrsToRemove: AttributeFuncs::typeIncompatible( |
| 7067 | Ty: CI->getArgOperand(i: ArgNo)->getType(), |
| 7068 | AS: CI->getParamAttributes(ArgNo))); |
| 7069 | } |
| 7070 | } |
| 7071 | |
| 7072 | // Look for functions that rely on old function attribute behavior. |
| 7073 | UpgradeFunctionAttributes(F&: *F); |
| 7074 | |
| 7075 | // Bring in any functions that this function forward-referenced via |
| 7076 | // blockaddresses. |
| 7077 | return materializeForwardReferencedFunctions(); |
| 7078 | } |
| 7079 | |
| 7080 | Error BitcodeReader::materializeModule() { |
| 7081 | if (Error Err = materializeMetadata()) |
| 7082 | return Err; |
| 7083 | |
| 7084 | // Promise to materialize all forward references. |
| 7085 | WillMaterializeAllForwardRefs = true; |
| 7086 | |
| 7087 | // Iterate over the module, deserializing any functions that are still on |
| 7088 | // disk. |
| 7089 | for (Function &F : *TheModule) { |
| 7090 | if (Error Err = materialize(GV: &F)) |
| 7091 | return Err; |
| 7092 | } |
| 7093 | // At this point, if there are any function bodies, parse the rest of |
| 7094 | // the bits in the module past the last function block we have recorded |
| 7095 | // through either lazy scanning or the VST. |
| 7096 | if (LastFunctionBlockBit || NextUnreadBit) |
| 7097 | if (Error Err = parseModule(ResumeBit: LastFunctionBlockBit > NextUnreadBit |
| 7098 | ? LastFunctionBlockBit |
| 7099 | : NextUnreadBit)) |
| 7100 | return Err; |
| 7101 | |
| 7102 | // Check that all block address forward references got resolved (as we |
| 7103 | // promised above). |
| 7104 | if (!BasicBlockFwdRefs.empty()) |
| 7105 | return error(Message: "Never resolved function from blockaddress" ); |
| 7106 | |
| 7107 | // Upgrade any intrinsic calls that slipped through (should not happen!) and |
| 7108 | // delete the old functions to clean up. We can't do this unless the entire |
| 7109 | // module is materialized because there could always be another function body |
| 7110 | // with calls to the old function. |
| 7111 | for (auto &I : UpgradedIntrinsics) { |
| 7112 | for (auto *U : I.first->users()) { |
| 7113 | if (CallInst *CI = dyn_cast<CallInst>(Val: U)) |
| 7114 | UpgradeIntrinsicCall(CB: CI, NewFn: I.second); |
| 7115 | } |
| 7116 | if (!I.first->use_empty()) |
| 7117 | I.first->replaceAllUsesWith(V: I.second); |
| 7118 | I.first->eraseFromParent(); |
| 7119 | } |
| 7120 | UpgradedIntrinsics.clear(); |
| 7121 | |
| 7122 | UpgradeDebugInfo(M&: *TheModule); |
| 7123 | |
| 7124 | UpgradeModuleFlags(M&: *TheModule); |
| 7125 | |
| 7126 | UpgradeNVVMAnnotations(M&: *TheModule); |
| 7127 | |
| 7128 | UpgradeARCRuntime(M&: *TheModule); |
| 7129 | |
| 7130 | return Error::success(); |
| 7131 | } |
| 7132 | |
| 7133 | std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { |
| 7134 | return IdentifiedStructTypes; |
| 7135 | } |
| 7136 | |
| 7137 | ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( |
| 7138 | BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, |
| 7139 | StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing) |
| 7140 | : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), |
| 7141 | ModulePath(ModulePath), IsPrevailing(IsPrevailing) {} |
| 7142 | |
| 7143 | void ModuleSummaryIndexBitcodeReader::addThisModule() { |
| 7144 | TheIndex.addModule(ModPath: ModulePath); |
| 7145 | } |
| 7146 | |
| 7147 | ModuleSummaryIndex::ModuleInfo * |
| 7148 | ModuleSummaryIndexBitcodeReader::getThisModule() { |
| 7149 | return TheIndex.getModule(ModPath: ModulePath); |
| 7150 | } |
| 7151 | |
| 7152 | template <bool AllowNullValueInfo> |
| 7153 | std::pair<ValueInfo, GlobalValue::GUID> |
| 7154 | ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { |
| 7155 | auto VGI = ValueIdToValueInfoMap[ValueId]; |
| 7156 | // We can have a null value info for memprof callsite info records in |
| 7157 | // distributed ThinLTO index files when the callee function summary is not |
| 7158 | // included in the index. The bitcode writer records 0 in that case, |
| 7159 | // and the caller of this helper will set AllowNullValueInfo to true. |
| 7160 | assert(AllowNullValueInfo || std::get<0>(VGI)); |
| 7161 | return VGI; |
| 7162 | } |
| 7163 | |
| 7164 | void ModuleSummaryIndexBitcodeReader::setValueGUID( |
| 7165 | uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, |
| 7166 | StringRef SourceFileName) { |
| 7167 | std::string GlobalId = |
| 7168 | GlobalValue::getGlobalIdentifier(Name: ValueName, Linkage, FileName: SourceFileName); |
| 7169 | auto ValueGUID = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: GlobalId); |
| 7170 | auto OriginalNameID = ValueGUID; |
| 7171 | if (GlobalValue::isLocalLinkage(Linkage)) |
| 7172 | OriginalNameID = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: ValueName); |
| 7173 | if (PrintSummaryGUIDs) |
| 7174 | dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " |
| 7175 | << ValueName << "\n" ; |
| 7176 | |
| 7177 | // UseStrtab is false for legacy summary formats and value names are |
| 7178 | // created on stack. In that case we save the name in a string saver in |
| 7179 | // the index so that the value name can be recorded. |
| 7180 | ValueIdToValueInfoMap[ValueID] = std::make_pair( |
| 7181 | x: TheIndex.getOrInsertValueInfo( |
| 7182 | GUID: ValueGUID, Name: UseStrtab ? ValueName : TheIndex.saveString(String: ValueName)), |
| 7183 | y&: OriginalNameID); |
| 7184 | } |
| 7185 | |
| 7186 | // Specialized value symbol table parser used when reading module index |
| 7187 | // blocks where we don't actually create global values. The parsed information |
| 7188 | // is saved in the bitcode reader for use when later parsing summaries. |
| 7189 | Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( |
| 7190 | uint64_t Offset, |
| 7191 | DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { |
| 7192 | // With a strtab the VST is not required to parse the summary. |
| 7193 | if (UseStrtab) |
| 7194 | return Error::success(); |
| 7195 | |
| 7196 | assert(Offset > 0 && "Expected non-zero VST offset" ); |
| 7197 | Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); |
| 7198 | if (!MaybeCurrentBit) |
| 7199 | return MaybeCurrentBit.takeError(); |
| 7200 | uint64_t CurrentBit = MaybeCurrentBit.get(); |
| 7201 | |
| 7202 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::VALUE_SYMTAB_BLOCK_ID)) |
| 7203 | return Err; |
| 7204 | |
| 7205 | SmallVector<uint64_t, 64> Record; |
| 7206 | |
| 7207 | // Read all the records for this value table. |
| 7208 | SmallString<128> ValueName; |
| 7209 | |
| 7210 | while (true) { |
| 7211 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 7212 | if (!MaybeEntry) |
| 7213 | return MaybeEntry.takeError(); |
| 7214 | BitstreamEntry Entry = MaybeEntry.get(); |
| 7215 | |
| 7216 | switch (Entry.Kind) { |
| 7217 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 7218 | case BitstreamEntry::Error: |
| 7219 | return error(Message: "Malformed block" ); |
| 7220 | case BitstreamEntry::EndBlock: |
| 7221 | // Done parsing VST, jump back to wherever we came from. |
| 7222 | if (Error JumpFailed = Stream.JumpToBit(BitNo: CurrentBit)) |
| 7223 | return JumpFailed; |
| 7224 | return Error::success(); |
| 7225 | case BitstreamEntry::Record: |
| 7226 | // The interesting case. |
| 7227 | break; |
| 7228 | } |
| 7229 | |
| 7230 | // Read a record. |
| 7231 | Record.clear(); |
| 7232 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 7233 | if (!MaybeRecord) |
| 7234 | return MaybeRecord.takeError(); |
| 7235 | switch (MaybeRecord.get()) { |
| 7236 | default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). |
| 7237 | break; |
| 7238 | case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] |
| 7239 | if (convertToString(Record, Idx: 1, Result&: ValueName)) |
| 7240 | return error(Message: "Invalid record" ); |
| 7241 | unsigned ValueID = Record[0]; |
| 7242 | assert(!SourceFileName.empty()); |
| 7243 | auto VLI = ValueIdToLinkageMap.find(Val: ValueID); |
| 7244 | assert(VLI != ValueIdToLinkageMap.end() && |
| 7245 | "No linkage found for VST entry?" ); |
| 7246 | auto Linkage = VLI->second; |
| 7247 | setValueGUID(ValueID, ValueName, Linkage, SourceFileName); |
| 7248 | ValueName.clear(); |
| 7249 | break; |
| 7250 | } |
| 7251 | case bitc::VST_CODE_FNENTRY: { |
| 7252 | // VST_CODE_FNENTRY: [valueid, offset, namechar x N] |
| 7253 | if (convertToString(Record, Idx: 2, Result&: ValueName)) |
| 7254 | return error(Message: "Invalid record" ); |
| 7255 | unsigned ValueID = Record[0]; |
| 7256 | assert(!SourceFileName.empty()); |
| 7257 | auto VLI = ValueIdToLinkageMap.find(Val: ValueID); |
| 7258 | assert(VLI != ValueIdToLinkageMap.end() && |
| 7259 | "No linkage found for VST entry?" ); |
| 7260 | auto Linkage = VLI->second; |
| 7261 | setValueGUID(ValueID, ValueName, Linkage, SourceFileName); |
| 7262 | ValueName.clear(); |
| 7263 | break; |
| 7264 | } |
| 7265 | case bitc::VST_CODE_COMBINED_ENTRY: { |
| 7266 | // VST_CODE_COMBINED_ENTRY: [valueid, refguid] |
| 7267 | unsigned ValueID = Record[0]; |
| 7268 | GlobalValue::GUID RefGUID = Record[1]; |
| 7269 | // The "original name", which is the second value of the pair will be |
| 7270 | // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. |
| 7271 | ValueIdToValueInfoMap[ValueID] = |
| 7272 | std::make_pair(x: TheIndex.getOrInsertValueInfo(GUID: RefGUID), y&: RefGUID); |
| 7273 | break; |
| 7274 | } |
| 7275 | } |
| 7276 | } |
| 7277 | } |
| 7278 | |
| 7279 | // Parse just the blocks needed for building the index out of the module. |
| 7280 | // At the end of this routine the module Index is populated with a map |
| 7281 | // from global value id to GlobalValueSummary objects. |
| 7282 | Error ModuleSummaryIndexBitcodeReader::parseModule() { |
| 7283 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID)) |
| 7284 | return Err; |
| 7285 | |
| 7286 | SmallVector<uint64_t, 64> Record; |
| 7287 | DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; |
| 7288 | unsigned ValueId = 0; |
| 7289 | |
| 7290 | // Read the index for this module. |
| 7291 | while (true) { |
| 7292 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
| 7293 | if (!MaybeEntry) |
| 7294 | return MaybeEntry.takeError(); |
| 7295 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
| 7296 | |
| 7297 | switch (Entry.Kind) { |
| 7298 | case BitstreamEntry::Error: |
| 7299 | return error(Message: "Malformed block" ); |
| 7300 | case BitstreamEntry::EndBlock: |
| 7301 | return Error::success(); |
| 7302 | |
| 7303 | case BitstreamEntry::SubBlock: |
| 7304 | switch (Entry.ID) { |
| 7305 | default: // Skip unknown content. |
| 7306 | if (Error Err = Stream.SkipBlock()) |
| 7307 | return Err; |
| 7308 | break; |
| 7309 | case bitc::BLOCKINFO_BLOCK_ID: |
| 7310 | // Need to parse these to get abbrev ids (e.g. for VST) |
| 7311 | if (Error Err = readBlockInfo()) |
| 7312 | return Err; |
| 7313 | break; |
| 7314 | case bitc::VALUE_SYMTAB_BLOCK_ID: |
| 7315 | // Should have been parsed earlier via VSTOffset, unless there |
| 7316 | // is no summary section. |
| 7317 | assert(((SeenValueSymbolTable && VSTOffset > 0) || |
| 7318 | !SeenGlobalValSummary) && |
| 7319 | "Expected early VST parse via VSTOffset record" ); |
| 7320 | if (Error Err = Stream.SkipBlock()) |
| 7321 | return Err; |
| 7322 | break; |
| 7323 | case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: |
| 7324 | case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: |
| 7325 | // Add the module if it is a per-module index (has a source file name). |
| 7326 | if (!SourceFileName.empty()) |
| 7327 | addThisModule(); |
| 7328 | assert(!SeenValueSymbolTable && |
| 7329 | "Already read VST when parsing summary block?" ); |
| 7330 | // We might not have a VST if there were no values in the |
| 7331 | // summary. An empty summary block generated when we are |
| 7332 | // performing ThinLTO compiles so we don't later invoke |
| 7333 | // the regular LTO process on them. |
| 7334 | if (VSTOffset > 0) { |
| 7335 | if (Error Err = parseValueSymbolTable(Offset: VSTOffset, ValueIdToLinkageMap)) |
| 7336 | return Err; |
| 7337 | SeenValueSymbolTable = true; |
| 7338 | } |
| 7339 | SeenGlobalValSummary = true; |
| 7340 | if (Error Err = parseEntireSummary(ID: Entry.ID)) |
| 7341 | return Err; |
| 7342 | break; |
| 7343 | case bitc::MODULE_STRTAB_BLOCK_ID: |
| 7344 | if (Error Err = parseModuleStringTable()) |
| 7345 | return Err; |
| 7346 | break; |
| 7347 | } |
| 7348 | continue; |
| 7349 | |
| 7350 | case BitstreamEntry::Record: { |
| 7351 | Record.clear(); |
| 7352 | Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 7353 | if (!MaybeBitCode) |
| 7354 | return MaybeBitCode.takeError(); |
| 7355 | switch (MaybeBitCode.get()) { |
| 7356 | default: |
| 7357 | break; // Default behavior, ignore unknown content. |
| 7358 | case bitc::MODULE_CODE_VERSION: { |
| 7359 | if (Error Err = parseVersionRecord(Record).takeError()) |
| 7360 | return Err; |
| 7361 | break; |
| 7362 | } |
| 7363 | /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] |
| 7364 | case bitc::MODULE_CODE_SOURCE_FILENAME: { |
| 7365 | SmallString<128> ValueName; |
| 7366 | if (convertToString(Record, Idx: 0, Result&: ValueName)) |
| 7367 | return error(Message: "Invalid record" ); |
| 7368 | SourceFileName = ValueName.c_str(); |
| 7369 | break; |
| 7370 | } |
| 7371 | /// MODULE_CODE_HASH: [5*i32] |
| 7372 | case bitc::MODULE_CODE_HASH: { |
| 7373 | if (Record.size() != 5) |
| 7374 | return error(Message: "Invalid hash length " + Twine(Record.size()).str()); |
| 7375 | auto &Hash = getThisModule()->second; |
| 7376 | int Pos = 0; |
| 7377 | for (auto &Val : Record) { |
| 7378 | assert(!(Val >> 32) && "Unexpected high bits set" ); |
| 7379 | Hash[Pos++] = Val; |
| 7380 | } |
| 7381 | break; |
| 7382 | } |
| 7383 | /// MODULE_CODE_VSTOFFSET: [offset] |
| 7384 | case bitc::MODULE_CODE_VSTOFFSET: |
| 7385 | if (Record.empty()) |
| 7386 | return error(Message: "Invalid record" ); |
| 7387 | // Note that we subtract 1 here because the offset is relative to one |
| 7388 | // word before the start of the identification or module block, which |
| 7389 | // was historically always the start of the regular bitcode header. |
| 7390 | VSTOffset = Record[0] - 1; |
| 7391 | break; |
| 7392 | // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] |
| 7393 | // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] |
| 7394 | // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] |
| 7395 | // v2: [strtab offset, strtab size, v1] |
| 7396 | case bitc::MODULE_CODE_GLOBALVAR: |
| 7397 | case bitc::MODULE_CODE_FUNCTION: |
| 7398 | case bitc::MODULE_CODE_ALIAS: { |
| 7399 | StringRef Name; |
| 7400 | ArrayRef<uint64_t> GVRecord; |
| 7401 | std::tie(args&: Name, args&: GVRecord) = readNameFromStrtab(Record); |
| 7402 | if (GVRecord.size() <= 3) |
| 7403 | return error(Message: "Invalid record" ); |
| 7404 | uint64_t RawLinkage = GVRecord[3]; |
| 7405 | GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Val: RawLinkage); |
| 7406 | if (!UseStrtab) { |
| 7407 | ValueIdToLinkageMap[ValueId++] = Linkage; |
| 7408 | break; |
| 7409 | } |
| 7410 | |
| 7411 | setValueGUID(ValueID: ValueId++, ValueName: Name, Linkage, SourceFileName); |
| 7412 | break; |
| 7413 | } |
| 7414 | } |
| 7415 | } |
| 7416 | continue; |
| 7417 | } |
| 7418 | } |
| 7419 | } |
| 7420 | |
| 7421 | SmallVector<ValueInfo, 0> |
| 7422 | ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { |
| 7423 | SmallVector<ValueInfo, 0> Ret; |
| 7424 | Ret.reserve(N: Record.size()); |
| 7425 | for (uint64_t RefValueId : Record) |
| 7426 | Ret.push_back(Elt: std::get<0>(in: getValueInfoFromValueId(ValueId: RefValueId))); |
| 7427 | return Ret; |
| 7428 | } |
| 7429 | |
| 7430 | SmallVector<FunctionSummary::EdgeTy, 0> |
| 7431 | ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, |
| 7432 | bool IsOldProfileFormat, |
| 7433 | bool HasProfile, bool HasRelBF) { |
| 7434 | SmallVector<FunctionSummary::EdgeTy, 0> Ret; |
| 7435 | // In the case of new profile formats, there are two Record entries per |
| 7436 | // Edge. Otherwise, conservatively reserve up to Record.size. |
| 7437 | if (!IsOldProfileFormat && (HasProfile || HasRelBF)) |
| 7438 | Ret.reserve(N: Record.size() / 2); |
| 7439 | else |
| 7440 | Ret.reserve(N: Record.size()); |
| 7441 | |
| 7442 | for (unsigned I = 0, E = Record.size(); I != E; ++I) { |
| 7443 | CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; |
| 7444 | bool HasTailCall = false; |
| 7445 | uint64_t RelBF = 0; |
| 7446 | ValueInfo Callee = std::get<0>(in: getValueInfoFromValueId(ValueId: Record[I])); |
| 7447 | if (IsOldProfileFormat) { |
| 7448 | I += 1; // Skip old callsitecount field |
| 7449 | if (HasProfile) |
| 7450 | I += 1; // Skip old profilecount field |
| 7451 | } else if (HasProfile) |
| 7452 | std::tie(args&: Hotness, args&: HasTailCall) = |
| 7453 | getDecodedHotnessCallEdgeInfo(RawFlags: Record[++I]); |
| 7454 | else if (HasRelBF) |
| 7455 | getDecodedRelBFCallEdgeInfo(RawFlags: Record[++I], RelBF, HasTailCall); |
| 7456 | Ret.push_back(Elt: FunctionSummary::EdgeTy{ |
| 7457 | Callee, CalleeInfo(Hotness, HasTailCall, RelBF)}); |
| 7458 | } |
| 7459 | return Ret; |
| 7460 | } |
| 7461 | |
| 7462 | static void |
| 7463 | parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, |
| 7464 | WholeProgramDevirtResolution &Wpd) { |
| 7465 | uint64_t ArgNum = Record[Slot++]; |
| 7466 | WholeProgramDevirtResolution::ByArg &B = |
| 7467 | Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; |
| 7468 | Slot += ArgNum; |
| 7469 | |
| 7470 | B.TheKind = |
| 7471 | static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); |
| 7472 | B.Info = Record[Slot++]; |
| 7473 | B.Byte = Record[Slot++]; |
| 7474 | B.Bit = Record[Slot++]; |
| 7475 | } |
| 7476 | |
| 7477 | static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, |
| 7478 | StringRef Strtab, size_t &Slot, |
| 7479 | TypeIdSummary &TypeId) { |
| 7480 | uint64_t Id = Record[Slot++]; |
| 7481 | WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; |
| 7482 | |
| 7483 | Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); |
| 7484 | Wpd.SingleImplName = {Strtab.data() + Record[Slot], |
| 7485 | static_cast<size_t>(Record[Slot + 1])}; |
| 7486 | Slot += 2; |
| 7487 | |
| 7488 | uint64_t ResByArgNum = Record[Slot++]; |
| 7489 | for (uint64_t I = 0; I != ResByArgNum; ++I) |
| 7490 | parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); |
| 7491 | } |
| 7492 | |
| 7493 | static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, |
| 7494 | StringRef Strtab, |
| 7495 | ModuleSummaryIndex &TheIndex) { |
| 7496 | size_t Slot = 0; |
| 7497 | TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( |
| 7498 | TypeId: {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); |
| 7499 | Slot += 2; |
| 7500 | |
| 7501 | TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); |
| 7502 | TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; |
| 7503 | TypeId.TTRes.AlignLog2 = Record[Slot++]; |
| 7504 | TypeId.TTRes.SizeM1 = Record[Slot++]; |
| 7505 | TypeId.TTRes.BitMask = Record[Slot++]; |
| 7506 | TypeId.TTRes.InlineBits = Record[Slot++]; |
| 7507 | |
| 7508 | while (Slot < Record.size()) |
| 7509 | parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); |
| 7510 | } |
| 7511 | |
| 7512 | std::vector<FunctionSummary::ParamAccess> |
| 7513 | ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { |
| 7514 | auto ReadRange = [&]() { |
| 7515 | APInt Lower(FunctionSummary::ParamAccess::RangeWidth, |
| 7516 | BitcodeReader::decodeSignRotatedValue(V: Record.front())); |
| 7517 | Record = Record.drop_front(); |
| 7518 | APInt Upper(FunctionSummary::ParamAccess::RangeWidth, |
| 7519 | BitcodeReader::decodeSignRotatedValue(V: Record.front())); |
| 7520 | Record = Record.drop_front(); |
| 7521 | ConstantRange Range{Lower, Upper}; |
| 7522 | assert(!Range.isFullSet()); |
| 7523 | assert(!Range.isUpperSignWrapped()); |
| 7524 | return Range; |
| 7525 | }; |
| 7526 | |
| 7527 | std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; |
| 7528 | while (!Record.empty()) { |
| 7529 | PendingParamAccesses.emplace_back(); |
| 7530 | FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); |
| 7531 | ParamAccess.ParamNo = Record.front(); |
| 7532 | Record = Record.drop_front(); |
| 7533 | ParamAccess.Use = ReadRange(); |
| 7534 | ParamAccess.Calls.resize(new_size: Record.front()); |
| 7535 | Record = Record.drop_front(); |
| 7536 | for (auto &Call : ParamAccess.Calls) { |
| 7537 | Call.ParamNo = Record.front(); |
| 7538 | Record = Record.drop_front(); |
| 7539 | Call.Callee = std::get<0>(in: getValueInfoFromValueId(ValueId: Record.front())); |
| 7540 | Record = Record.drop_front(); |
| 7541 | Call.Offsets = ReadRange(); |
| 7542 | } |
| 7543 | } |
| 7544 | return PendingParamAccesses; |
| 7545 | } |
| 7546 | |
| 7547 | void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( |
| 7548 | ArrayRef<uint64_t> Record, size_t &Slot, |
| 7549 | TypeIdCompatibleVtableInfo &TypeId) { |
| 7550 | uint64_t Offset = Record[Slot++]; |
| 7551 | ValueInfo Callee = std::get<0>(in: getValueInfoFromValueId(ValueId: Record[Slot++])); |
| 7552 | TypeId.push_back(x: {Offset, Callee}); |
| 7553 | } |
| 7554 | |
| 7555 | void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( |
| 7556 | ArrayRef<uint64_t> Record) { |
| 7557 | size_t Slot = 0; |
| 7558 | TypeIdCompatibleVtableInfo &TypeId = |
| 7559 | TheIndex.getOrInsertTypeIdCompatibleVtableSummary( |
| 7560 | TypeId: {Strtab.data() + Record[Slot], |
| 7561 | static_cast<size_t>(Record[Slot + 1])}); |
| 7562 | Slot += 2; |
| 7563 | |
| 7564 | while (Slot < Record.size()) |
| 7565 | parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); |
| 7566 | } |
| 7567 | |
| 7568 | SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext( |
| 7569 | ArrayRef<uint64_t> Record, unsigned &I) { |
| 7570 | SmallVector<unsigned> StackIdList; |
| 7571 | // For backwards compatibility with old format before radix tree was |
| 7572 | // used, simply see if we found a radix tree array record (and thus if |
| 7573 | // the RadixArray is non-empty). |
| 7574 | if (RadixArray.empty()) { |
| 7575 | unsigned NumStackEntries = Record[I++]; |
| 7576 | assert(Record.size() - I >= NumStackEntries); |
| 7577 | StackIdList.reserve(N: NumStackEntries); |
| 7578 | for (unsigned J = 0; J < NumStackEntries; J++) { |
| 7579 | assert(Record[I] < StackIds.size()); |
| 7580 | StackIdList.push_back( |
| 7581 | Elt: TheIndex.addOrGetStackIdIndex(StackId: StackIds[Record[I++]])); |
| 7582 | } |
| 7583 | } else { |
| 7584 | unsigned RadixIndex = Record[I++]; |
| 7585 | // See the comments above CallStackRadixTreeBuilder in ProfileData/MemProf.h |
| 7586 | // for a detailed description of the radix tree array format. Briefly, the |
| 7587 | // first entry will be the number of frames, any negative values are the |
| 7588 | // negative of the offset of the next frame, and otherwise the frames are in |
| 7589 | // increasing linear order. |
| 7590 | assert(RadixIndex < RadixArray.size()); |
| 7591 | unsigned NumStackIds = RadixArray[RadixIndex++]; |
| 7592 | StackIdList.reserve(N: NumStackIds); |
| 7593 | while (NumStackIds--) { |
| 7594 | assert(RadixIndex < RadixArray.size()); |
| 7595 | unsigned Elem = RadixArray[RadixIndex]; |
| 7596 | if (static_cast<std::make_signed_t<unsigned>>(Elem) < 0) { |
| 7597 | RadixIndex = RadixIndex - Elem; |
| 7598 | assert(RadixIndex < RadixArray.size()); |
| 7599 | Elem = RadixArray[RadixIndex]; |
| 7600 | // We shouldn't encounter a second offset in a row. |
| 7601 | assert(static_cast<std::make_signed_t<unsigned>>(Elem) >= 0); |
| 7602 | } |
| 7603 | RadixIndex++; |
| 7604 | StackIdList.push_back(Elt: TheIndex.addOrGetStackIdIndex(StackId: StackIds[Elem])); |
| 7605 | } |
| 7606 | } |
| 7607 | return StackIdList; |
| 7608 | } |
| 7609 | |
| 7610 | static void setSpecialRefs(SmallVectorImpl<ValueInfo> &Refs, unsigned ROCnt, |
| 7611 | unsigned WOCnt) { |
| 7612 | // Readonly and writeonly refs are in the end of the refs list. |
| 7613 | assert(ROCnt + WOCnt <= Refs.size()); |
| 7614 | unsigned FirstWORef = Refs.size() - WOCnt; |
| 7615 | unsigned RefNo = FirstWORef - ROCnt; |
| 7616 | for (; RefNo < FirstWORef; ++RefNo) |
| 7617 | Refs[RefNo].setReadOnly(); |
| 7618 | for (; RefNo < Refs.size(); ++RefNo) |
| 7619 | Refs[RefNo].setWriteOnly(); |
| 7620 | } |
| 7621 | |
| 7622 | // Eagerly parse the entire summary block. This populates the GlobalValueSummary |
| 7623 | // objects in the index. |
| 7624 | Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { |
| 7625 | if (Error Err = Stream.EnterSubBlock(BlockID: ID)) |
| 7626 | return Err; |
| 7627 | SmallVector<uint64_t, 64> Record; |
| 7628 | |
| 7629 | // Parse version |
| 7630 | { |
| 7631 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 7632 | if (!MaybeEntry) |
| 7633 | return MaybeEntry.takeError(); |
| 7634 | BitstreamEntry Entry = MaybeEntry.get(); |
| 7635 | |
| 7636 | if (Entry.Kind != BitstreamEntry::Record) |
| 7637 | return error(Message: "Invalid Summary Block: record for version expected" ); |
| 7638 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 7639 | if (!MaybeRecord) |
| 7640 | return MaybeRecord.takeError(); |
| 7641 | if (MaybeRecord.get() != bitc::FS_VERSION) |
| 7642 | return error(Message: "Invalid Summary Block: version expected" ); |
| 7643 | } |
| 7644 | const uint64_t Version = Record[0]; |
| 7645 | const bool IsOldProfileFormat = Version == 1; |
| 7646 | if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) |
| 7647 | return error(Message: "Invalid summary version " + Twine(Version) + |
| 7648 | ". Version should be in the range [1-" + |
| 7649 | Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + |
| 7650 | "]." ); |
| 7651 | Record.clear(); |
| 7652 | |
| 7653 | // Keep around the last seen summary to be used when we see an optional |
| 7654 | // "OriginalName" attachement. |
| 7655 | GlobalValueSummary *LastSeenSummary = nullptr; |
| 7656 | GlobalValue::GUID LastSeenGUID = 0; |
| 7657 | |
| 7658 | // We can expect to see any number of type ID information records before |
| 7659 | // each function summary records; these variables store the information |
| 7660 | // collected so far so that it can be used to create the summary object. |
| 7661 | std::vector<GlobalValue::GUID> PendingTypeTests; |
| 7662 | std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, |
| 7663 | PendingTypeCheckedLoadVCalls; |
| 7664 | std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, |
| 7665 | PendingTypeCheckedLoadConstVCalls; |
| 7666 | std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; |
| 7667 | |
| 7668 | std::vector<CallsiteInfo> PendingCallsites; |
| 7669 | std::vector<AllocInfo> PendingAllocs; |
| 7670 | std::vector<uint64_t> PendingContextIds; |
| 7671 | |
| 7672 | while (true) { |
| 7673 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 7674 | if (!MaybeEntry) |
| 7675 | return MaybeEntry.takeError(); |
| 7676 | BitstreamEntry Entry = MaybeEntry.get(); |
| 7677 | |
| 7678 | switch (Entry.Kind) { |
| 7679 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 7680 | case BitstreamEntry::Error: |
| 7681 | return error(Message: "Malformed block" ); |
| 7682 | case BitstreamEntry::EndBlock: |
| 7683 | return Error::success(); |
| 7684 | case BitstreamEntry::Record: |
| 7685 | // The interesting case. |
| 7686 | break; |
| 7687 | } |
| 7688 | |
| 7689 | // Read a record. The record format depends on whether this |
| 7690 | // is a per-module index or a combined index file. In the per-module |
| 7691 | // case the records contain the associated value's ID for correlation |
| 7692 | // with VST entries. In the combined index the correlation is done |
| 7693 | // via the bitcode offset of the summary records (which were saved |
| 7694 | // in the combined index VST entries). The records also contain |
| 7695 | // information used for ThinLTO renaming and importing. |
| 7696 | Record.clear(); |
| 7697 | Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 7698 | if (!MaybeBitCode) |
| 7699 | return MaybeBitCode.takeError(); |
| 7700 | switch (unsigned BitCode = MaybeBitCode.get()) { |
| 7701 | default: // Default behavior: ignore. |
| 7702 | break; |
| 7703 | case bitc::FS_FLAGS: { // [flags] |
| 7704 | TheIndex.setFlags(Record[0]); |
| 7705 | break; |
| 7706 | } |
| 7707 | case bitc::FS_VALUE_GUID: { // [valueid, refguid_upper32, refguid_lower32] |
| 7708 | uint64_t ValueID = Record[0]; |
| 7709 | GlobalValue::GUID RefGUID; |
| 7710 | if (Version >= 11) { |
| 7711 | RefGUID = Record[1] << 32 | Record[2]; |
| 7712 | } else { |
| 7713 | RefGUID = Record[1]; |
| 7714 | } |
| 7715 | ValueIdToValueInfoMap[ValueID] = |
| 7716 | std::make_pair(x: TheIndex.getOrInsertValueInfo(GUID: RefGUID), y&: RefGUID); |
| 7717 | break; |
| 7718 | } |
| 7719 | // FS_PERMODULE is legacy and does not have support for the tail call flag. |
| 7720 | // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, |
| 7721 | // numrefs x valueid, n x (valueid)] |
| 7722 | // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, |
| 7723 | // numrefs x valueid, |
| 7724 | // n x (valueid, hotness+tailcall flags)] |
| 7725 | // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, |
| 7726 | // numrefs x valueid, |
| 7727 | // n x (valueid, relblockfreq+tailcall)] |
| 7728 | case bitc::FS_PERMODULE: |
| 7729 | case bitc::FS_PERMODULE_RELBF: |
| 7730 | case bitc::FS_PERMODULE_PROFILE: { |
| 7731 | unsigned ValueID = Record[0]; |
| 7732 | uint64_t RawFlags = Record[1]; |
| 7733 | unsigned InstCount = Record[2]; |
| 7734 | uint64_t RawFunFlags = 0; |
| 7735 | unsigned NumRefs = Record[3]; |
| 7736 | unsigned NumRORefs = 0, NumWORefs = 0; |
| 7737 | int RefListStartIndex = 4; |
| 7738 | if (Version >= 4) { |
| 7739 | RawFunFlags = Record[3]; |
| 7740 | NumRefs = Record[4]; |
| 7741 | RefListStartIndex = 5; |
| 7742 | if (Version >= 5) { |
| 7743 | NumRORefs = Record[5]; |
| 7744 | RefListStartIndex = 6; |
| 7745 | if (Version >= 7) { |
| 7746 | NumWORefs = Record[6]; |
| 7747 | RefListStartIndex = 7; |
| 7748 | } |
| 7749 | } |
| 7750 | } |
| 7751 | |
| 7752 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
| 7753 | // The module path string ref set in the summary must be owned by the |
| 7754 | // index's module string table. Since we don't have a module path |
| 7755 | // string table section in the per-module index, we create a single |
| 7756 | // module path string table entry with an empty (0) ID to take |
| 7757 | // ownership. |
| 7758 | int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; |
| 7759 | assert(Record.size() >= RefListStartIndex + NumRefs && |
| 7760 | "Record size inconsistent with number of references" ); |
| 7761 | SmallVector<ValueInfo, 0> Refs = makeRefList( |
| 7762 | Record: ArrayRef<uint64_t>(Record).slice(N: RefListStartIndex, M: NumRefs)); |
| 7763 | bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); |
| 7764 | bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); |
| 7765 | SmallVector<FunctionSummary::EdgeTy, 0> Calls = makeCallList( |
| 7766 | Record: ArrayRef<uint64_t>(Record).slice(N: CallGraphEdgeStartIndex), |
| 7767 | IsOldProfileFormat, HasProfile, HasRelBF); |
| 7768 | setSpecialRefs(Refs, ROCnt: NumRORefs, WOCnt: NumWORefs); |
| 7769 | auto VIAndOriginalGUID = getValueInfoFromValueId(ValueId: ValueID); |
| 7770 | // In order to save memory, only record the memprof summaries if this is |
| 7771 | // the prevailing copy of a symbol. The linker doesn't resolve local |
| 7772 | // linkage values so don't check whether those are prevailing. |
| 7773 | auto LT = (GlobalValue::LinkageTypes)Flags.Linkage; |
| 7774 | if (IsPrevailing && !GlobalValue::isLocalLinkage(Linkage: LT) && |
| 7775 | !IsPrevailing(VIAndOriginalGUID.first.getGUID())) { |
| 7776 | PendingCallsites.clear(); |
| 7777 | PendingAllocs.clear(); |
| 7778 | } |
| 7779 | auto FS = std::make_unique<FunctionSummary>( |
| 7780 | args&: Flags, args&: InstCount, args: getDecodedFFlags(RawFlags: RawFunFlags), args: std::move(Refs), |
| 7781 | args: std::move(Calls), args: std::move(PendingTypeTests), |
| 7782 | args: std::move(PendingTypeTestAssumeVCalls), |
| 7783 | args: std::move(PendingTypeCheckedLoadVCalls), |
| 7784 | args: std::move(PendingTypeTestAssumeConstVCalls), |
| 7785 | args: std::move(PendingTypeCheckedLoadConstVCalls), |
| 7786 | args: std::move(PendingParamAccesses), args: std::move(PendingCallsites), |
| 7787 | args: std::move(PendingAllocs)); |
| 7788 | FS->setModulePath(getThisModule()->first()); |
| 7789 | FS->setOriginalName(std::get<1>(in&: VIAndOriginalGUID)); |
| 7790 | TheIndex.addGlobalValueSummary(VI: std::get<0>(in&: VIAndOriginalGUID), |
| 7791 | Summary: std::move(FS)); |
| 7792 | break; |
| 7793 | } |
| 7794 | // FS_ALIAS: [valueid, flags, valueid] |
| 7795 | // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as |
| 7796 | // they expect all aliasee summaries to be available. |
| 7797 | case bitc::FS_ALIAS: { |
| 7798 | unsigned ValueID = Record[0]; |
| 7799 | uint64_t RawFlags = Record[1]; |
| 7800 | unsigned AliaseeID = Record[2]; |
| 7801 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
| 7802 | auto AS = std::make_unique<AliasSummary>(args&: Flags); |
| 7803 | // The module path string ref set in the summary must be owned by the |
| 7804 | // index's module string table. Since we don't have a module path |
| 7805 | // string table section in the per-module index, we create a single |
| 7806 | // module path string table entry with an empty (0) ID to take |
| 7807 | // ownership. |
| 7808 | AS->setModulePath(getThisModule()->first()); |
| 7809 | |
| 7810 | auto AliaseeVI = std::get<0>(in: getValueInfoFromValueId(ValueId: AliaseeID)); |
| 7811 | auto AliaseeInModule = TheIndex.findSummaryInModule(VI: AliaseeVI, ModuleId: ModulePath); |
| 7812 | if (!AliaseeInModule) |
| 7813 | return error(Message: "Alias expects aliasee summary to be parsed" ); |
| 7814 | AS->setAliasee(AliaseeVI, Aliasee: AliaseeInModule); |
| 7815 | |
| 7816 | auto GUID = getValueInfoFromValueId(ValueId: ValueID); |
| 7817 | AS->setOriginalName(std::get<1>(in&: GUID)); |
| 7818 | TheIndex.addGlobalValueSummary(VI: std::get<0>(in&: GUID), Summary: std::move(AS)); |
| 7819 | break; |
| 7820 | } |
| 7821 | // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] |
| 7822 | case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { |
| 7823 | unsigned ValueID = Record[0]; |
| 7824 | uint64_t RawFlags = Record[1]; |
| 7825 | unsigned RefArrayStart = 2; |
| 7826 | GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, |
| 7827 | /* WriteOnly */ false, |
| 7828 | /* Constant */ false, |
| 7829 | GlobalObject::VCallVisibilityPublic); |
| 7830 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
| 7831 | if (Version >= 5) { |
| 7832 | GVF = getDecodedGVarFlags(RawFlags: Record[2]); |
| 7833 | RefArrayStart = 3; |
| 7834 | } |
| 7835 | SmallVector<ValueInfo, 0> Refs = |
| 7836 | makeRefList(Record: ArrayRef<uint64_t>(Record).slice(N: RefArrayStart)); |
| 7837 | auto FS = |
| 7838 | std::make_unique<GlobalVarSummary>(args&: Flags, args&: GVF, args: std::move(Refs)); |
| 7839 | FS->setModulePath(getThisModule()->first()); |
| 7840 | auto GUID = getValueInfoFromValueId(ValueId: ValueID); |
| 7841 | FS->setOriginalName(std::get<1>(in&: GUID)); |
| 7842 | TheIndex.addGlobalValueSummary(VI: std::get<0>(in&: GUID), Summary: std::move(FS)); |
| 7843 | break; |
| 7844 | } |
| 7845 | // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, |
| 7846 | // numrefs, numrefs x valueid, |
| 7847 | // n x (valueid, offset)] |
| 7848 | case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { |
| 7849 | unsigned ValueID = Record[0]; |
| 7850 | uint64_t RawFlags = Record[1]; |
| 7851 | GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(RawFlags: Record[2]); |
| 7852 | unsigned NumRefs = Record[3]; |
| 7853 | unsigned RefListStartIndex = 4; |
| 7854 | unsigned VTableListStartIndex = RefListStartIndex + NumRefs; |
| 7855 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
| 7856 | SmallVector<ValueInfo, 0> Refs = makeRefList( |
| 7857 | Record: ArrayRef<uint64_t>(Record).slice(N: RefListStartIndex, M: NumRefs)); |
| 7858 | VTableFuncList VTableFuncs; |
| 7859 | for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { |
| 7860 | ValueInfo Callee = std::get<0>(in: getValueInfoFromValueId(ValueId: Record[I])); |
| 7861 | uint64_t Offset = Record[++I]; |
| 7862 | VTableFuncs.push_back(x: {Callee, Offset}); |
| 7863 | } |
| 7864 | auto VS = |
| 7865 | std::make_unique<GlobalVarSummary>(args&: Flags, args&: GVF, args: std::move(Refs)); |
| 7866 | VS->setModulePath(getThisModule()->first()); |
| 7867 | VS->setVTableFuncs(VTableFuncs); |
| 7868 | auto GUID = getValueInfoFromValueId(ValueId: ValueID); |
| 7869 | VS->setOriginalName(std::get<1>(in&: GUID)); |
| 7870 | TheIndex.addGlobalValueSummary(VI: std::get<0>(in&: GUID), Summary: std::move(VS)); |
| 7871 | break; |
| 7872 | } |
| 7873 | // FS_COMBINED is legacy and does not have support for the tail call flag. |
| 7874 | // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, |
| 7875 | // numrefs x valueid, n x (valueid)] |
| 7876 | // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, |
| 7877 | // numrefs x valueid, |
| 7878 | // n x (valueid, hotness+tailcall flags)] |
| 7879 | case bitc::FS_COMBINED: |
| 7880 | case bitc::FS_COMBINED_PROFILE: { |
| 7881 | unsigned ValueID = Record[0]; |
| 7882 | uint64_t ModuleId = Record[1]; |
| 7883 | uint64_t RawFlags = Record[2]; |
| 7884 | unsigned InstCount = Record[3]; |
| 7885 | uint64_t RawFunFlags = 0; |
| 7886 | unsigned NumRefs = Record[4]; |
| 7887 | unsigned NumRORefs = 0, NumWORefs = 0; |
| 7888 | int RefListStartIndex = 5; |
| 7889 | |
| 7890 | if (Version >= 4) { |
| 7891 | RawFunFlags = Record[4]; |
| 7892 | RefListStartIndex = 6; |
| 7893 | size_t NumRefsIndex = 5; |
| 7894 | if (Version >= 5) { |
| 7895 | unsigned NumRORefsOffset = 1; |
| 7896 | RefListStartIndex = 7; |
| 7897 | if (Version >= 6) { |
| 7898 | NumRefsIndex = 6; |
| 7899 | RefListStartIndex = 8; |
| 7900 | if (Version >= 7) { |
| 7901 | RefListStartIndex = 9; |
| 7902 | NumWORefs = Record[8]; |
| 7903 | NumRORefsOffset = 2; |
| 7904 | } |
| 7905 | } |
| 7906 | NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; |
| 7907 | } |
| 7908 | NumRefs = Record[NumRefsIndex]; |
| 7909 | } |
| 7910 | |
| 7911 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
| 7912 | int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; |
| 7913 | assert(Record.size() >= RefListStartIndex + NumRefs && |
| 7914 | "Record size inconsistent with number of references" ); |
| 7915 | SmallVector<ValueInfo, 0> Refs = makeRefList( |
| 7916 | Record: ArrayRef<uint64_t>(Record).slice(N: RefListStartIndex, M: NumRefs)); |
| 7917 | bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); |
| 7918 | SmallVector<FunctionSummary::EdgeTy, 0> Edges = makeCallList( |
| 7919 | Record: ArrayRef<uint64_t>(Record).slice(N: CallGraphEdgeStartIndex), |
| 7920 | IsOldProfileFormat, HasProfile, HasRelBF: false); |
| 7921 | ValueInfo VI = std::get<0>(in: getValueInfoFromValueId(ValueId: ValueID)); |
| 7922 | setSpecialRefs(Refs, ROCnt: NumRORefs, WOCnt: NumWORefs); |
| 7923 | auto FS = std::make_unique<FunctionSummary>( |
| 7924 | args&: Flags, args&: InstCount, args: getDecodedFFlags(RawFlags: RawFunFlags), args: std::move(Refs), |
| 7925 | args: std::move(Edges), args: std::move(PendingTypeTests), |
| 7926 | args: std::move(PendingTypeTestAssumeVCalls), |
| 7927 | args: std::move(PendingTypeCheckedLoadVCalls), |
| 7928 | args: std::move(PendingTypeTestAssumeConstVCalls), |
| 7929 | args: std::move(PendingTypeCheckedLoadConstVCalls), |
| 7930 | args: std::move(PendingParamAccesses), args: std::move(PendingCallsites), |
| 7931 | args: std::move(PendingAllocs)); |
| 7932 | LastSeenSummary = FS.get(); |
| 7933 | LastSeenGUID = VI.getGUID(); |
| 7934 | FS->setModulePath(ModuleIdMap[ModuleId]); |
| 7935 | TheIndex.addGlobalValueSummary(VI, Summary: std::move(FS)); |
| 7936 | break; |
| 7937 | } |
| 7938 | // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] |
| 7939 | // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as |
| 7940 | // they expect all aliasee summaries to be available. |
| 7941 | case bitc::FS_COMBINED_ALIAS: { |
| 7942 | unsigned ValueID = Record[0]; |
| 7943 | uint64_t ModuleId = Record[1]; |
| 7944 | uint64_t RawFlags = Record[2]; |
| 7945 | unsigned AliaseeValueId = Record[3]; |
| 7946 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
| 7947 | auto AS = std::make_unique<AliasSummary>(args&: Flags); |
| 7948 | LastSeenSummary = AS.get(); |
| 7949 | AS->setModulePath(ModuleIdMap[ModuleId]); |
| 7950 | |
| 7951 | auto AliaseeVI = std::get<0>(in: getValueInfoFromValueId(ValueId: AliaseeValueId)); |
| 7952 | auto AliaseeInModule = TheIndex.findSummaryInModule(VI: AliaseeVI, ModuleId: AS->modulePath()); |
| 7953 | AS->setAliasee(AliaseeVI, Aliasee: AliaseeInModule); |
| 7954 | |
| 7955 | ValueInfo VI = std::get<0>(in: getValueInfoFromValueId(ValueId: ValueID)); |
| 7956 | LastSeenGUID = VI.getGUID(); |
| 7957 | TheIndex.addGlobalValueSummary(VI, Summary: std::move(AS)); |
| 7958 | break; |
| 7959 | } |
| 7960 | // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] |
| 7961 | case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { |
| 7962 | unsigned ValueID = Record[0]; |
| 7963 | uint64_t ModuleId = Record[1]; |
| 7964 | uint64_t RawFlags = Record[2]; |
| 7965 | unsigned RefArrayStart = 3; |
| 7966 | GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, |
| 7967 | /* WriteOnly */ false, |
| 7968 | /* Constant */ false, |
| 7969 | GlobalObject::VCallVisibilityPublic); |
| 7970 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
| 7971 | if (Version >= 5) { |
| 7972 | GVF = getDecodedGVarFlags(RawFlags: Record[3]); |
| 7973 | RefArrayStart = 4; |
| 7974 | } |
| 7975 | SmallVector<ValueInfo, 0> Refs = |
| 7976 | makeRefList(Record: ArrayRef<uint64_t>(Record).slice(N: RefArrayStart)); |
| 7977 | auto FS = |
| 7978 | std::make_unique<GlobalVarSummary>(args&: Flags, args&: GVF, args: std::move(Refs)); |
| 7979 | LastSeenSummary = FS.get(); |
| 7980 | FS->setModulePath(ModuleIdMap[ModuleId]); |
| 7981 | ValueInfo VI = std::get<0>(in: getValueInfoFromValueId(ValueId: ValueID)); |
| 7982 | LastSeenGUID = VI.getGUID(); |
| 7983 | TheIndex.addGlobalValueSummary(VI, Summary: std::move(FS)); |
| 7984 | break; |
| 7985 | } |
| 7986 | // FS_COMBINED_ORIGINAL_NAME: [original_name] |
| 7987 | case bitc::FS_COMBINED_ORIGINAL_NAME: { |
| 7988 | uint64_t OriginalName = Record[0]; |
| 7989 | if (!LastSeenSummary) |
| 7990 | return error(Message: "Name attachment that does not follow a combined record" ); |
| 7991 | LastSeenSummary->setOriginalName(OriginalName); |
| 7992 | TheIndex.addOriginalName(ValueGUID: LastSeenGUID, OrigGUID: OriginalName); |
| 7993 | // Reset the LastSeenSummary |
| 7994 | LastSeenSummary = nullptr; |
| 7995 | LastSeenGUID = 0; |
| 7996 | break; |
| 7997 | } |
| 7998 | case bitc::FS_TYPE_TESTS: |
| 7999 | assert(PendingTypeTests.empty()); |
| 8000 | llvm::append_range(C&: PendingTypeTests, R&: Record); |
| 8001 | break; |
| 8002 | |
| 8003 | case bitc::FS_TYPE_TEST_ASSUME_VCALLS: |
| 8004 | assert(PendingTypeTestAssumeVCalls.empty()); |
| 8005 | for (unsigned I = 0; I != Record.size(); I += 2) |
| 8006 | PendingTypeTestAssumeVCalls.push_back(x: {.GUID: Record[I], .Offset: Record[I+1]}); |
| 8007 | break; |
| 8008 | |
| 8009 | case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: |
| 8010 | assert(PendingTypeCheckedLoadVCalls.empty()); |
| 8011 | for (unsigned I = 0; I != Record.size(); I += 2) |
| 8012 | PendingTypeCheckedLoadVCalls.push_back(x: {.GUID: Record[I], .Offset: Record[I+1]}); |
| 8013 | break; |
| 8014 | |
| 8015 | case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: |
| 8016 | PendingTypeTestAssumeConstVCalls.push_back( |
| 8017 | x: {.VFunc: {.GUID: Record[0], .Offset: Record[1]}, .Args: {Record.begin() + 2, Record.end()}}); |
| 8018 | break; |
| 8019 | |
| 8020 | case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: |
| 8021 | PendingTypeCheckedLoadConstVCalls.push_back( |
| 8022 | x: {.VFunc: {.GUID: Record[0], .Offset: Record[1]}, .Args: {Record.begin() + 2, Record.end()}}); |
| 8023 | break; |
| 8024 | |
| 8025 | case bitc::FS_CFI_FUNCTION_DEFS: { |
| 8026 | auto &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); |
| 8027 | for (unsigned I = 0; I != Record.size(); I += 2) |
| 8028 | CfiFunctionDefs.emplace(A: Strtab.data() + Record[I], |
| 8029 | A: static_cast<size_t>(Record[I + 1])); |
| 8030 | break; |
| 8031 | } |
| 8032 | |
| 8033 | case bitc::FS_CFI_FUNCTION_DECLS: { |
| 8034 | auto &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); |
| 8035 | for (unsigned I = 0; I != Record.size(); I += 2) |
| 8036 | CfiFunctionDecls.emplace(A: Strtab.data() + Record[I], |
| 8037 | A: static_cast<size_t>(Record[I + 1])); |
| 8038 | break; |
| 8039 | } |
| 8040 | |
| 8041 | case bitc::FS_TYPE_ID: |
| 8042 | parseTypeIdSummaryRecord(Record, Strtab, TheIndex); |
| 8043 | break; |
| 8044 | |
| 8045 | case bitc::FS_TYPE_ID_METADATA: |
| 8046 | parseTypeIdCompatibleVtableSummaryRecord(Record); |
| 8047 | break; |
| 8048 | |
| 8049 | case bitc::FS_BLOCK_COUNT: |
| 8050 | TheIndex.addBlockCount(C: Record[0]); |
| 8051 | break; |
| 8052 | |
| 8053 | case bitc::FS_PARAM_ACCESS: { |
| 8054 | PendingParamAccesses = parseParamAccesses(Record); |
| 8055 | break; |
| 8056 | } |
| 8057 | |
| 8058 | case bitc::FS_STACK_IDS: { // [n x stackid] |
| 8059 | // Save stack ids in the reader to consult when adding stack ids from the |
| 8060 | // lists in the stack node and alloc node entries. |
| 8061 | if (Version <= 11) { |
| 8062 | StackIds = ArrayRef<uint64_t>(Record); |
| 8063 | break; |
| 8064 | } |
| 8065 | // This is an array of 32-bit fixed-width values, holding each 64-bit |
| 8066 | // context id as a pair of adjacent (most significant first) 32-bit words. |
| 8067 | assert(Record.size() % 2 == 0); |
| 8068 | StackIds.reserve(n: Record.size() / 2); |
| 8069 | for (auto R = Record.begin(); R != Record.end(); R += 2) |
| 8070 | StackIds.push_back(x: *R << 32 | *(R + 1)); |
| 8071 | break; |
| 8072 | } |
| 8073 | |
| 8074 | case bitc::FS_CONTEXT_RADIX_TREE_ARRAY: { // [n x entry] |
| 8075 | RadixArray = ArrayRef<uint64_t>(Record); |
| 8076 | break; |
| 8077 | } |
| 8078 | |
| 8079 | case bitc::FS_PERMODULE_CALLSITE_INFO: { |
| 8080 | unsigned ValueID = Record[0]; |
| 8081 | SmallVector<unsigned> StackIdList; |
| 8082 | for (uint64_t R : drop_begin(RangeOrContainer&: Record)) { |
| 8083 | assert(R < StackIds.size()); |
| 8084 | StackIdList.push_back(Elt: TheIndex.addOrGetStackIdIndex(StackId: StackIds[R])); |
| 8085 | } |
| 8086 | ValueInfo VI = std::get<0>(in: getValueInfoFromValueId(ValueId: ValueID)); |
| 8087 | PendingCallsites.push_back(x: CallsiteInfo({VI, std::move(StackIdList)})); |
| 8088 | break; |
| 8089 | } |
| 8090 | |
| 8091 | case bitc::FS_COMBINED_CALLSITE_INFO: { |
| 8092 | auto RecordIter = Record.begin(); |
| 8093 | unsigned ValueID = *RecordIter++; |
| 8094 | unsigned NumStackIds = *RecordIter++; |
| 8095 | unsigned NumVersions = *RecordIter++; |
| 8096 | assert(Record.size() == 3 + NumStackIds + NumVersions); |
| 8097 | SmallVector<unsigned> StackIdList; |
| 8098 | for (unsigned J = 0; J < NumStackIds; J++) { |
| 8099 | assert(*RecordIter < StackIds.size()); |
| 8100 | StackIdList.push_back( |
| 8101 | Elt: TheIndex.addOrGetStackIdIndex(StackId: StackIds[*RecordIter++])); |
| 8102 | } |
| 8103 | SmallVector<unsigned> Versions; |
| 8104 | for (unsigned J = 0; J < NumVersions; J++) |
| 8105 | Versions.push_back(Elt: *RecordIter++); |
| 8106 | ValueInfo VI = std::get<0>( |
| 8107 | in: getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueId: ValueID)); |
| 8108 | PendingCallsites.push_back( |
| 8109 | x: CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)})); |
| 8110 | break; |
| 8111 | } |
| 8112 | |
| 8113 | case bitc::FS_ALLOC_CONTEXT_IDS: { |
| 8114 | // This is an array of 32-bit fixed-width values, holding each 64-bit |
| 8115 | // context id as a pair of adjacent (most significant first) 32-bit words. |
| 8116 | assert(Record.size() % 2 == 0); |
| 8117 | PendingContextIds.reserve(n: Record.size() / 2); |
| 8118 | for (auto R = Record.begin(); R != Record.end(); R += 2) |
| 8119 | PendingContextIds.push_back(x: *R << 32 | *(R + 1)); |
| 8120 | break; |
| 8121 | } |
| 8122 | |
| 8123 | case bitc::FS_PERMODULE_ALLOC_INFO: { |
| 8124 | unsigned I = 0; |
| 8125 | std::vector<MIBInfo> MIBs; |
| 8126 | unsigned NumMIBs = 0; |
| 8127 | if (Version >= 10) |
| 8128 | NumMIBs = Record[I++]; |
| 8129 | unsigned MIBsRead = 0; |
| 8130 | while ((Version >= 10 && MIBsRead++ < NumMIBs) || |
| 8131 | (Version < 10 && I < Record.size())) { |
| 8132 | assert(Record.size() - I >= 2); |
| 8133 | AllocationType AllocType = (AllocationType)Record[I++]; |
| 8134 | auto StackIdList = parseAllocInfoContext(Record, I); |
| 8135 | MIBs.push_back(x: MIBInfo(AllocType, std::move(StackIdList))); |
| 8136 | } |
| 8137 | // We either have nothing left or at least NumMIBs context size info |
| 8138 | // indices left (for the total sizes included when reporting of hinted |
| 8139 | // bytes is enabled). |
| 8140 | assert(I == Record.size() || Record.size() - I >= NumMIBs); |
| 8141 | std::vector<std::vector<ContextTotalSize>> AllContextSizes; |
| 8142 | if (I < Record.size()) { |
| 8143 | assert(!PendingContextIds.empty() && |
| 8144 | "Missing context ids for alloc sizes" ); |
| 8145 | unsigned ContextIdIndex = 0; |
| 8146 | MIBsRead = 0; |
| 8147 | // The sizes are a linearized array of sizes, where for each MIB there |
| 8148 | // is 1 or more sizes (due to context trimming, each MIB in the metadata |
| 8149 | // and summarized here can correspond to more than one original context |
| 8150 | // from the profile). |
| 8151 | while (MIBsRead++ < NumMIBs) { |
| 8152 | // First read the number of contexts recorded for this MIB. |
| 8153 | unsigned NumContextSizeInfoEntries = Record[I++]; |
| 8154 | assert(Record.size() - I >= NumContextSizeInfoEntries); |
| 8155 | std::vector<ContextTotalSize> ContextSizes; |
| 8156 | ContextSizes.reserve(n: NumContextSizeInfoEntries); |
| 8157 | for (unsigned J = 0; J < NumContextSizeInfoEntries; J++) { |
| 8158 | assert(ContextIdIndex < PendingContextIds.size()); |
| 8159 | // Skip any 0 entries for MIBs without the context size info. |
| 8160 | if (PendingContextIds[ContextIdIndex] == 0) { |
| 8161 | // The size should also be 0 if the context was 0. |
| 8162 | assert(!Record[I]); |
| 8163 | ContextIdIndex++; |
| 8164 | I++; |
| 8165 | continue; |
| 8166 | } |
| 8167 | // PendingContextIds read from the preceding FS_ALLOC_CONTEXT_IDS |
| 8168 | // should be in the same order as the total sizes. |
| 8169 | ContextSizes.push_back( |
| 8170 | x: {.FullStackId: PendingContextIds[ContextIdIndex++], .TotalSize: Record[I++]}); |
| 8171 | } |
| 8172 | AllContextSizes.push_back(x: std::move(ContextSizes)); |
| 8173 | } |
| 8174 | PendingContextIds.clear(); |
| 8175 | } |
| 8176 | PendingAllocs.push_back(x: AllocInfo(std::move(MIBs))); |
| 8177 | if (!AllContextSizes.empty()) { |
| 8178 | assert(PendingAllocs.back().MIBs.size() == AllContextSizes.size()); |
| 8179 | PendingAllocs.back().ContextSizeInfos = std::move(AllContextSizes); |
| 8180 | } |
| 8181 | break; |
| 8182 | } |
| 8183 | |
| 8184 | case bitc::FS_COMBINED_ALLOC_INFO: |
| 8185 | case bitc::FS_COMBINED_ALLOC_INFO_NO_CONTEXT: { |
| 8186 | unsigned I = 0; |
| 8187 | std::vector<MIBInfo> MIBs; |
| 8188 | unsigned NumMIBs = Record[I++]; |
| 8189 | unsigned NumVersions = Record[I++]; |
| 8190 | unsigned MIBsRead = 0; |
| 8191 | while (MIBsRead++ < NumMIBs) { |
| 8192 | assert(Record.size() - I >= 2); |
| 8193 | AllocationType AllocType = (AllocationType)Record[I++]; |
| 8194 | SmallVector<unsigned> StackIdList; |
| 8195 | if (BitCode == bitc::FS_COMBINED_ALLOC_INFO) |
| 8196 | StackIdList = parseAllocInfoContext(Record, I); |
| 8197 | MIBs.push_back(x: MIBInfo(AllocType, std::move(StackIdList))); |
| 8198 | } |
| 8199 | assert(Record.size() - I >= NumVersions); |
| 8200 | SmallVector<uint8_t> Versions; |
| 8201 | for (unsigned J = 0; J < NumVersions; J++) |
| 8202 | Versions.push_back(Elt: Record[I++]); |
| 8203 | assert(I == Record.size()); |
| 8204 | PendingAllocs.push_back(x: AllocInfo(std::move(Versions), std::move(MIBs))); |
| 8205 | break; |
| 8206 | } |
| 8207 | } |
| 8208 | } |
| 8209 | llvm_unreachable("Exit infinite loop" ); |
| 8210 | } |
| 8211 | |
| 8212 | // Parse the module string table block into the Index. |
| 8213 | // This populates the ModulePathStringTable map in the index. |
| 8214 | Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { |
| 8215 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_STRTAB_BLOCK_ID)) |
| 8216 | return Err; |
| 8217 | |
| 8218 | SmallVector<uint64_t, 64> Record; |
| 8219 | |
| 8220 | SmallString<128> ModulePath; |
| 8221 | ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; |
| 8222 | |
| 8223 | while (true) { |
| 8224 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
| 8225 | if (!MaybeEntry) |
| 8226 | return MaybeEntry.takeError(); |
| 8227 | BitstreamEntry Entry = MaybeEntry.get(); |
| 8228 | |
| 8229 | switch (Entry.Kind) { |
| 8230 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 8231 | case BitstreamEntry::Error: |
| 8232 | return error(Message: "Malformed block" ); |
| 8233 | case BitstreamEntry::EndBlock: |
| 8234 | return Error::success(); |
| 8235 | case BitstreamEntry::Record: |
| 8236 | // The interesting case. |
| 8237 | break; |
| 8238 | } |
| 8239 | |
| 8240 | Record.clear(); |
| 8241 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 8242 | if (!MaybeRecord) |
| 8243 | return MaybeRecord.takeError(); |
| 8244 | switch (MaybeRecord.get()) { |
| 8245 | default: // Default behavior: ignore. |
| 8246 | break; |
| 8247 | case bitc::MST_CODE_ENTRY: { |
| 8248 | // MST_ENTRY: [modid, namechar x N] |
| 8249 | uint64_t ModuleId = Record[0]; |
| 8250 | |
| 8251 | if (convertToString(Record, Idx: 1, Result&: ModulePath)) |
| 8252 | return error(Message: "Invalid record" ); |
| 8253 | |
| 8254 | LastSeenModule = TheIndex.addModule(ModPath: ModulePath); |
| 8255 | ModuleIdMap[ModuleId] = LastSeenModule->first(); |
| 8256 | |
| 8257 | ModulePath.clear(); |
| 8258 | break; |
| 8259 | } |
| 8260 | /// MST_CODE_HASH: [5*i32] |
| 8261 | case bitc::MST_CODE_HASH: { |
| 8262 | if (Record.size() != 5) |
| 8263 | return error(Message: "Invalid hash length " + Twine(Record.size()).str()); |
| 8264 | if (!LastSeenModule) |
| 8265 | return error(Message: "Invalid hash that does not follow a module path" ); |
| 8266 | int Pos = 0; |
| 8267 | for (auto &Val : Record) { |
| 8268 | assert(!(Val >> 32) && "Unexpected high bits set" ); |
| 8269 | LastSeenModule->second[Pos++] = Val; |
| 8270 | } |
| 8271 | // Reset LastSeenModule to avoid overriding the hash unexpectedly. |
| 8272 | LastSeenModule = nullptr; |
| 8273 | break; |
| 8274 | } |
| 8275 | } |
| 8276 | } |
| 8277 | llvm_unreachable("Exit infinite loop" ); |
| 8278 | } |
| 8279 | |
| 8280 | namespace { |
| 8281 | |
| 8282 | // FIXME: This class is only here to support the transition to llvm::Error. It |
| 8283 | // will be removed once this transition is complete. Clients should prefer to |
| 8284 | // deal with the Error value directly, rather than converting to error_code. |
| 8285 | class BitcodeErrorCategoryType : public std::error_category { |
| 8286 | const char *name() const noexcept override { |
| 8287 | return "llvm.bitcode" ; |
| 8288 | } |
| 8289 | |
| 8290 | std::string message(int IE) const override { |
| 8291 | BitcodeError E = static_cast<BitcodeError>(IE); |
| 8292 | switch (E) { |
| 8293 | case BitcodeError::CorruptedBitcode: |
| 8294 | return "Corrupted bitcode" ; |
| 8295 | } |
| 8296 | llvm_unreachable("Unknown error type!" ); |
| 8297 | } |
| 8298 | }; |
| 8299 | |
| 8300 | } // end anonymous namespace |
| 8301 | |
| 8302 | const std::error_category &llvm::BitcodeErrorCategory() { |
| 8303 | static BitcodeErrorCategoryType ErrorCategory; |
| 8304 | return ErrorCategory; |
| 8305 | } |
| 8306 | |
| 8307 | static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, |
| 8308 | unsigned Block, unsigned RecordID) { |
| 8309 | if (Error Err = Stream.EnterSubBlock(BlockID: Block)) |
| 8310 | return std::move(Err); |
| 8311 | |
| 8312 | StringRef Strtab; |
| 8313 | while (true) { |
| 8314 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
| 8315 | if (!MaybeEntry) |
| 8316 | return MaybeEntry.takeError(); |
| 8317 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
| 8318 | |
| 8319 | switch (Entry.Kind) { |
| 8320 | case BitstreamEntry::EndBlock: |
| 8321 | return Strtab; |
| 8322 | |
| 8323 | case BitstreamEntry::Error: |
| 8324 | return error(Message: "Malformed block" ); |
| 8325 | |
| 8326 | case BitstreamEntry::SubBlock: |
| 8327 | if (Error Err = Stream.SkipBlock()) |
| 8328 | return std::move(Err); |
| 8329 | break; |
| 8330 | |
| 8331 | case BitstreamEntry::Record: |
| 8332 | StringRef Blob; |
| 8333 | SmallVector<uint64_t, 1> Record; |
| 8334 | Expected<unsigned> MaybeRecord = |
| 8335 | Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
| 8336 | if (!MaybeRecord) |
| 8337 | return MaybeRecord.takeError(); |
| 8338 | if (MaybeRecord.get() == RecordID) |
| 8339 | Strtab = Blob; |
| 8340 | break; |
| 8341 | } |
| 8342 | } |
| 8343 | } |
| 8344 | |
| 8345 | //===----------------------------------------------------------------------===// |
| 8346 | // External interface |
| 8347 | //===----------------------------------------------------------------------===// |
| 8348 | |
| 8349 | Expected<std::vector<BitcodeModule>> |
| 8350 | llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { |
| 8351 | auto FOrErr = getBitcodeFileContents(Buffer); |
| 8352 | if (!FOrErr) |
| 8353 | return FOrErr.takeError(); |
| 8354 | return std::move(FOrErr->Mods); |
| 8355 | } |
| 8356 | |
| 8357 | Expected<BitcodeFileContents> |
| 8358 | llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { |
| 8359 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); |
| 8360 | if (!StreamOrErr) |
| 8361 | return StreamOrErr.takeError(); |
| 8362 | BitstreamCursor &Stream = *StreamOrErr; |
| 8363 | |
| 8364 | BitcodeFileContents F; |
| 8365 | while (true) { |
| 8366 | uint64_t BCBegin = Stream.getCurrentByteNo(); |
| 8367 | |
| 8368 | // We may be consuming bitcode from a client that leaves garbage at the end |
| 8369 | // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to |
| 8370 | // the end that there cannot possibly be another module, stop looking. |
| 8371 | if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) |
| 8372 | return F; |
| 8373 | |
| 8374 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
| 8375 | if (!MaybeEntry) |
| 8376 | return MaybeEntry.takeError(); |
| 8377 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
| 8378 | |
| 8379 | switch (Entry.Kind) { |
| 8380 | case BitstreamEntry::EndBlock: |
| 8381 | case BitstreamEntry::Error: |
| 8382 | return error(Message: "Malformed block" ); |
| 8383 | |
| 8384 | case BitstreamEntry::SubBlock: { |
| 8385 | uint64_t IdentificationBit = -1ull; |
| 8386 | if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { |
| 8387 | IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; |
| 8388 | if (Error Err = Stream.SkipBlock()) |
| 8389 | return std::move(Err); |
| 8390 | |
| 8391 | { |
| 8392 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
| 8393 | if (!MaybeEntry) |
| 8394 | return MaybeEntry.takeError(); |
| 8395 | Entry = MaybeEntry.get(); |
| 8396 | } |
| 8397 | |
| 8398 | if (Entry.Kind != BitstreamEntry::SubBlock || |
| 8399 | Entry.ID != bitc::MODULE_BLOCK_ID) |
| 8400 | return error(Message: "Malformed block" ); |
| 8401 | } |
| 8402 | |
| 8403 | if (Entry.ID == bitc::MODULE_BLOCK_ID) { |
| 8404 | uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; |
| 8405 | if (Error Err = Stream.SkipBlock()) |
| 8406 | return std::move(Err); |
| 8407 | |
| 8408 | F.Mods.push_back(x: {Stream.getBitcodeBytes().slice( |
| 8409 | N: BCBegin, M: Stream.getCurrentByteNo() - BCBegin), |
| 8410 | Buffer.getBufferIdentifier(), IdentificationBit, |
| 8411 | ModuleBit}); |
| 8412 | continue; |
| 8413 | } |
| 8414 | |
| 8415 | if (Entry.ID == bitc::STRTAB_BLOCK_ID) { |
| 8416 | Expected<StringRef> Strtab = |
| 8417 | readBlobInRecord(Stream, Block: bitc::STRTAB_BLOCK_ID, RecordID: bitc::STRTAB_BLOB); |
| 8418 | if (!Strtab) |
| 8419 | return Strtab.takeError(); |
| 8420 | // This string table is used by every preceding bitcode module that does |
| 8421 | // not have its own string table. A bitcode file may have multiple |
| 8422 | // string tables if it was created by binary concatenation, for example |
| 8423 | // with "llvm-cat -b". |
| 8424 | for (BitcodeModule &I : llvm::reverse(C&: F.Mods)) { |
| 8425 | if (!I.Strtab.empty()) |
| 8426 | break; |
| 8427 | I.Strtab = *Strtab; |
| 8428 | } |
| 8429 | // Similarly, the string table is used by every preceding symbol table; |
| 8430 | // normally there will be just one unless the bitcode file was created |
| 8431 | // by binary concatenation. |
| 8432 | if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) |
| 8433 | F.StrtabForSymtab = *Strtab; |
| 8434 | continue; |
| 8435 | } |
| 8436 | |
| 8437 | if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { |
| 8438 | Expected<StringRef> SymtabOrErr = |
| 8439 | readBlobInRecord(Stream, Block: bitc::SYMTAB_BLOCK_ID, RecordID: bitc::SYMTAB_BLOB); |
| 8440 | if (!SymtabOrErr) |
| 8441 | return SymtabOrErr.takeError(); |
| 8442 | |
| 8443 | // We can expect the bitcode file to have multiple symbol tables if it |
| 8444 | // was created by binary concatenation. In that case we silently |
| 8445 | // ignore any subsequent symbol tables, which is fine because this is a |
| 8446 | // low level function. The client is expected to notice that the number |
| 8447 | // of modules in the symbol table does not match the number of modules |
| 8448 | // in the input file and regenerate the symbol table. |
| 8449 | if (F.Symtab.empty()) |
| 8450 | F.Symtab = *SymtabOrErr; |
| 8451 | continue; |
| 8452 | } |
| 8453 | |
| 8454 | if (Error Err = Stream.SkipBlock()) |
| 8455 | return std::move(Err); |
| 8456 | continue; |
| 8457 | } |
| 8458 | case BitstreamEntry::Record: |
| 8459 | if (Error E = Stream.skipRecord(AbbrevID: Entry.ID).takeError()) |
| 8460 | return std::move(E); |
| 8461 | continue; |
| 8462 | } |
| 8463 | } |
| 8464 | } |
| 8465 | |
| 8466 | /// Get a lazy one-at-time loading module from bitcode. |
| 8467 | /// |
| 8468 | /// This isn't always used in a lazy context. In particular, it's also used by |
| 8469 | /// \a parseModule(). If this is truly lazy, then we need to eagerly pull |
| 8470 | /// in forward-referenced functions from block address references. |
| 8471 | /// |
| 8472 | /// \param[in] MaterializeAll Set to \c true if we should materialize |
| 8473 | /// everything. |
| 8474 | Expected<std::unique_ptr<Module>> |
| 8475 | BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, |
| 8476 | bool ShouldLazyLoadMetadata, bool IsImporting, |
| 8477 | ParserCallbacks Callbacks) { |
| 8478 | BitstreamCursor Stream(Buffer); |
| 8479 | |
| 8480 | std::string ProducerIdentification; |
| 8481 | if (IdentificationBit != -1ull) { |
| 8482 | if (Error JumpFailed = Stream.JumpToBit(BitNo: IdentificationBit)) |
| 8483 | return std::move(JumpFailed); |
| 8484 | if (Error E = |
| 8485 | readIdentificationBlock(Stream).moveInto(Value&: ProducerIdentification)) |
| 8486 | return std::move(E); |
| 8487 | } |
| 8488 | |
| 8489 | if (Error JumpFailed = Stream.JumpToBit(BitNo: ModuleBit)) |
| 8490 | return std::move(JumpFailed); |
| 8491 | auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, |
| 8492 | Context); |
| 8493 | |
| 8494 | std::unique_ptr<Module> M = |
| 8495 | std::make_unique<Module>(args&: ModuleIdentifier, args&: Context); |
| 8496 | M->setMaterializer(R); |
| 8497 | |
| 8498 | // Delay parsing Metadata if ShouldLazyLoadMetadata is true. |
| 8499 | if (Error Err = R->parseBitcodeInto(M: M.get(), ShouldLazyLoadMetadata, |
| 8500 | IsImporting, Callbacks)) |
| 8501 | return std::move(Err); |
| 8502 | |
| 8503 | if (MaterializeAll) { |
| 8504 | // Read in the entire module, and destroy the BitcodeReader. |
| 8505 | if (Error Err = M->materializeAll()) |
| 8506 | return std::move(Err); |
| 8507 | } else { |
| 8508 | // Resolve forward references from blockaddresses. |
| 8509 | if (Error Err = R->materializeForwardReferencedFunctions()) |
| 8510 | return std::move(Err); |
| 8511 | } |
| 8512 | |
| 8513 | return std::move(M); |
| 8514 | } |
| 8515 | |
| 8516 | Expected<std::unique_ptr<Module>> |
| 8517 | BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, |
| 8518 | bool IsImporting, ParserCallbacks Callbacks) { |
| 8519 | return getModuleImpl(Context, MaterializeAll: false, ShouldLazyLoadMetadata, IsImporting, |
| 8520 | Callbacks); |
| 8521 | } |
| 8522 | |
| 8523 | // Parse the specified bitcode buffer and merge the index into CombinedIndex. |
| 8524 | // We don't use ModuleIdentifier here because the client may need to control the |
| 8525 | // module path used in the combined summary (e.g. when reading summaries for |
| 8526 | // regular LTO modules). |
| 8527 | Error BitcodeModule::readSummary( |
| 8528 | ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, |
| 8529 | std::function<bool(GlobalValue::GUID)> IsPrevailing) { |
| 8530 | BitstreamCursor Stream(Buffer); |
| 8531 | if (Error JumpFailed = Stream.JumpToBit(BitNo: ModuleBit)) |
| 8532 | return JumpFailed; |
| 8533 | |
| 8534 | ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, |
| 8535 | ModulePath, IsPrevailing); |
| 8536 | return R.parseModule(); |
| 8537 | } |
| 8538 | |
| 8539 | // Parse the specified bitcode buffer, returning the function info index. |
| 8540 | Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { |
| 8541 | BitstreamCursor Stream(Buffer); |
| 8542 | if (Error JumpFailed = Stream.JumpToBit(BitNo: ModuleBit)) |
| 8543 | return std::move(JumpFailed); |
| 8544 | |
| 8545 | auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/args: false); |
| 8546 | ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, |
| 8547 | ModuleIdentifier, 0); |
| 8548 | |
| 8549 | if (Error Err = R.parseModule()) |
| 8550 | return std::move(Err); |
| 8551 | |
| 8552 | return std::move(Index); |
| 8553 | } |
| 8554 | |
| 8555 | static Expected<std::pair<bool, bool>> |
| 8556 | getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, |
| 8557 | unsigned ID, |
| 8558 | BitcodeLTOInfo <OInfo) { |
| 8559 | if (Error Err = Stream.EnterSubBlock(BlockID: ID)) |
| 8560 | return std::move(Err); |
| 8561 | SmallVector<uint64_t, 64> Record; |
| 8562 | |
| 8563 | while (true) { |
| 8564 | BitstreamEntry Entry; |
| 8565 | std::pair<bool, bool> Result = {false,false}; |
| 8566 | if (Error E = Stream.advanceSkippingSubblocks().moveInto(Value&: Entry)) |
| 8567 | return std::move(E); |
| 8568 | |
| 8569 | switch (Entry.Kind) { |
| 8570 | case BitstreamEntry::SubBlock: // Handled for us already. |
| 8571 | case BitstreamEntry::Error: |
| 8572 | return error(Message: "Malformed block" ); |
| 8573 | case BitstreamEntry::EndBlock: { |
| 8574 | // If no flags record found, set both flags to false. |
| 8575 | return Result; |
| 8576 | } |
| 8577 | case BitstreamEntry::Record: |
| 8578 | // The interesting case. |
| 8579 | break; |
| 8580 | } |
| 8581 | |
| 8582 | // Look for the FS_FLAGS record. |
| 8583 | Record.clear(); |
| 8584 | Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
| 8585 | if (!MaybeBitCode) |
| 8586 | return MaybeBitCode.takeError(); |
| 8587 | switch (MaybeBitCode.get()) { |
| 8588 | default: // Default behavior: ignore. |
| 8589 | break; |
| 8590 | case bitc::FS_FLAGS: { // [flags] |
| 8591 | uint64_t Flags = Record[0]; |
| 8592 | // Scan flags. |
| 8593 | assert(Flags <= 0x2ff && "Unexpected bits in flag" ); |
| 8594 | |
| 8595 | bool EnableSplitLTOUnit = Flags & 0x8; |
| 8596 | bool UnifiedLTO = Flags & 0x200; |
| 8597 | Result = {EnableSplitLTOUnit, UnifiedLTO}; |
| 8598 | |
| 8599 | return Result; |
| 8600 | } |
| 8601 | } |
| 8602 | } |
| 8603 | llvm_unreachable("Exit infinite loop" ); |
| 8604 | } |
| 8605 | |
| 8606 | // Check if the given bitcode buffer contains a global value summary block. |
| 8607 | Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { |
| 8608 | BitstreamCursor Stream(Buffer); |
| 8609 | if (Error JumpFailed = Stream.JumpToBit(BitNo: ModuleBit)) |
| 8610 | return std::move(JumpFailed); |
| 8611 | |
| 8612 | if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID)) |
| 8613 | return std::move(Err); |
| 8614 | |
| 8615 | while (true) { |
| 8616 | llvm::BitstreamEntry Entry; |
| 8617 | if (Error E = Stream.advance().moveInto(Value&: Entry)) |
| 8618 | return std::move(E); |
| 8619 | |
| 8620 | switch (Entry.Kind) { |
| 8621 | case BitstreamEntry::Error: |
| 8622 | return error(Message: "Malformed block" ); |
| 8623 | case BitstreamEntry::EndBlock: |
| 8624 | return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, |
| 8625 | /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false}; |
| 8626 | |
| 8627 | case BitstreamEntry::SubBlock: |
| 8628 | if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { |
| 8629 | BitcodeLTOInfo LTOInfo; |
| 8630 | Expected<std::pair<bool, bool>> Flags = |
| 8631 | getEnableSplitLTOUnitAndUnifiedFlag(Stream, ID: Entry.ID, LTOInfo); |
| 8632 | if (!Flags) |
| 8633 | return Flags.takeError(); |
| 8634 | std::tie(args&: LTOInfo.EnableSplitLTOUnit, args&: LTOInfo.UnifiedLTO) = Flags.get(); |
| 8635 | LTOInfo.IsThinLTO = true; |
| 8636 | LTOInfo.HasSummary = true; |
| 8637 | return LTOInfo; |
| 8638 | } |
| 8639 | |
| 8640 | if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { |
| 8641 | BitcodeLTOInfo LTOInfo; |
| 8642 | Expected<std::pair<bool, bool>> Flags = |
| 8643 | getEnableSplitLTOUnitAndUnifiedFlag(Stream, ID: Entry.ID, LTOInfo); |
| 8644 | if (!Flags) |
| 8645 | return Flags.takeError(); |
| 8646 | std::tie(args&: LTOInfo.EnableSplitLTOUnit, args&: LTOInfo.UnifiedLTO) = Flags.get(); |
| 8647 | LTOInfo.IsThinLTO = false; |
| 8648 | LTOInfo.HasSummary = true; |
| 8649 | return LTOInfo; |
| 8650 | } |
| 8651 | |
| 8652 | // Ignore other sub-blocks. |
| 8653 | if (Error Err = Stream.SkipBlock()) |
| 8654 | return std::move(Err); |
| 8655 | continue; |
| 8656 | |
| 8657 | case BitstreamEntry::Record: |
| 8658 | if (Expected<unsigned> StreamFailed = Stream.skipRecord(AbbrevID: Entry.ID)) |
| 8659 | continue; |
| 8660 | else |
| 8661 | return StreamFailed.takeError(); |
| 8662 | } |
| 8663 | } |
| 8664 | } |
| 8665 | |
| 8666 | static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { |
| 8667 | Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); |
| 8668 | if (!MsOrErr) |
| 8669 | return MsOrErr.takeError(); |
| 8670 | |
| 8671 | if (MsOrErr->size() != 1) |
| 8672 | return error(Message: "Expected a single module" ); |
| 8673 | |
| 8674 | return (*MsOrErr)[0]; |
| 8675 | } |
| 8676 | |
| 8677 | Expected<std::unique_ptr<Module>> |
| 8678 | llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, |
| 8679 | bool ShouldLazyLoadMetadata, bool IsImporting, |
| 8680 | ParserCallbacks Callbacks) { |
| 8681 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
| 8682 | if (!BM) |
| 8683 | return BM.takeError(); |
| 8684 | |
| 8685 | return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting, |
| 8686 | Callbacks); |
| 8687 | } |
| 8688 | |
| 8689 | Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( |
| 8690 | std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, |
| 8691 | bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) { |
| 8692 | auto MOrErr = getLazyBitcodeModule(Buffer: *Buffer, Context, ShouldLazyLoadMetadata, |
| 8693 | IsImporting, Callbacks); |
| 8694 | if (MOrErr) |
| 8695 | (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); |
| 8696 | return MOrErr; |
| 8697 | } |
| 8698 | |
| 8699 | Expected<std::unique_ptr<Module>> |
| 8700 | BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) { |
| 8701 | return getModuleImpl(Context, MaterializeAll: true, ShouldLazyLoadMetadata: false, IsImporting: false, Callbacks); |
| 8702 | // TODO: Restore the use-lists to the in-memory state when the bitcode was |
| 8703 | // written. We must defer until the Module has been fully materialized. |
| 8704 | } |
| 8705 | |
| 8706 | Expected<std::unique_ptr<Module>> |
| 8707 | llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, |
| 8708 | ParserCallbacks Callbacks) { |
| 8709 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
| 8710 | if (!BM) |
| 8711 | return BM.takeError(); |
| 8712 | |
| 8713 | return BM->parseModule(Context, Callbacks); |
| 8714 | } |
| 8715 | |
| 8716 | Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { |
| 8717 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); |
| 8718 | if (!StreamOrErr) |
| 8719 | return StreamOrErr.takeError(); |
| 8720 | |
| 8721 | return readTriple(Stream&: *StreamOrErr); |
| 8722 | } |
| 8723 | |
| 8724 | Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { |
| 8725 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); |
| 8726 | if (!StreamOrErr) |
| 8727 | return StreamOrErr.takeError(); |
| 8728 | |
| 8729 | return hasObjCCategory(Stream&: *StreamOrErr); |
| 8730 | } |
| 8731 | |
| 8732 | Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { |
| 8733 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); |
| 8734 | if (!StreamOrErr) |
| 8735 | return StreamOrErr.takeError(); |
| 8736 | |
| 8737 | return readIdentificationCode(Stream&: *StreamOrErr); |
| 8738 | } |
| 8739 | |
| 8740 | Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, |
| 8741 | ModuleSummaryIndex &CombinedIndex) { |
| 8742 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
| 8743 | if (!BM) |
| 8744 | return BM.takeError(); |
| 8745 | |
| 8746 | return BM->readSummary(CombinedIndex, ModulePath: BM->getModuleIdentifier()); |
| 8747 | } |
| 8748 | |
| 8749 | Expected<std::unique_ptr<ModuleSummaryIndex>> |
| 8750 | llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { |
| 8751 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
| 8752 | if (!BM) |
| 8753 | return BM.takeError(); |
| 8754 | |
| 8755 | return BM->getSummary(); |
| 8756 | } |
| 8757 | |
| 8758 | Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { |
| 8759 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
| 8760 | if (!BM) |
| 8761 | return BM.takeError(); |
| 8762 | |
| 8763 | return BM->getLTOInfo(); |
| 8764 | } |
| 8765 | |
| 8766 | Expected<std::unique_ptr<ModuleSummaryIndex>> |
| 8767 | llvm::getModuleSummaryIndexForFile(StringRef Path, |
| 8768 | bool IgnoreEmptyThinLTOIndexFile) { |
| 8769 | ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = |
| 8770 | MemoryBuffer::getFileOrSTDIN(Filename: Path); |
| 8771 | if (!FileOrErr) |
| 8772 | return errorCodeToError(EC: FileOrErr.getError()); |
| 8773 | if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) |
| 8774 | return nullptr; |
| 8775 | return getModuleSummaryIndex(Buffer: **FileOrErr); |
| 8776 | } |
| 8777 | |