Index: lib/IR/AsmWriter.cpp =================================================================== --- lib/IR/AsmWriter.cpp +++ lib/IR/AsmWriter.cpp @@ -3148,7 +3148,7 @@ if (MDs.empty()) return; - if (MDNames.empty()) + if (TheModule && MDNames.empty()) TheModule->getMDKindNames(MDNames); for (const auto &I : MDs) { Index: unittests/IR/AsmWriterTest.cpp =================================================================== --- /dev/null +++ unittests/IR/AsmWriterTest.cpp @@ -0,0 +1,58 @@ +//===- llvm/unittest/IR/AsmWriter.cpp - AsmWriter tests -------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/LLVMContext.h" +#include "llvm/IR/MDBuilder.h" +#include "llvm/IR/Module.h" +#include "gtest/gtest.h" + +using namespace llvm; + +namespace { + +TEST(AsmWriterTest, DebugPrintDetachedInstruction) { + LLVMContext Ctx; + Module Mod("MyModule", Ctx); + + // Create a tiny function with a couple of instructions. + FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), + /*isVarArg=*/false); + Function *F = Function::Create(FTy, Function::ExternalLinkage, "", &Mod); + BasicBlock *BB = BasicBlock::Create(Ctx, "", F); + + // Final instruction has branch weight meta-data so as to trigger + // the bug in question. + IRBuilder<> IBuilder(BB); + BasicBlock *TBB = BasicBlock::Create(Ctx, "", F); + BasicBlock *FBB = BasicBlock::Create(Ctx, "", F); + MDBuilder MDB(Ctx); + MDNode *Weights = MDB.createBranchWeights(42, 13); + Value *VT = IBuilder.getTrue(); + AllocaInst *Alloca1 = IBuilder.CreateAlloca(IBuilder.getInt32Ty()); + BranchInst *BI = IBuilder.CreateCondBr(VT, TBB, FBB, Weights); + + // PR24852: Insure that an instruction can be printed even when it + // has no parent. + { std::string S; + raw_string_ostream OS(S); + BI->print(OS); // with parent + EXPECT_EQ(OS.str(), " br i1 true, label %2, label %3, !prof !0"); + } + BI->removeFromParent(); + { std::string S; + raw_string_ostream OS(S); + BI->print(OS); // without parent + std::size_t r = OS.str().find("br i1 true, label %2, label %3, !insertAfter(Alloca1); // reparent so that it will be cleaned up +} + +} Index: unittests/IR/CMakeLists.txt =================================================================== --- unittests/IR/CMakeLists.txt +++ unittests/IR/CMakeLists.txt @@ -6,6 +6,7 @@ ) set(IRSources + AsmWriterTest.cpp AttributesTest.cpp ConstantRangeTest.cpp ConstantsTest.cpp