1287 lines · cpp
1//===- Cloning.cpp - Unit tests for the Cloner ----------------------------===//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "llvm/Transforms/Utils/Cloning.h"10#include "llvm/ADT/STLExtras.h"11#include "llvm/ADT/SmallPtrSet.h"12#include "llvm/Analysis/AliasAnalysis.h"13#include "llvm/Analysis/DomTreeUpdater.h"14#include "llvm/Analysis/LoopInfo.h"15#include "llvm/AsmParser/Parser.h"16#include "llvm/IR/Argument.h"17#include "llvm/IR/BasicBlock.h"18#include "llvm/IR/Constant.h"19#include "llvm/IR/DIBuilder.h"20#include "llvm/IR/DebugInfo.h"21#include "llvm/IR/DebugInfoMetadata.h"22#include "llvm/IR/Function.h"23#include "llvm/IR/IRBuilder.h"24#include "llvm/IR/InstIterator.h"25#include "llvm/IR/Instruction.h"26#include "llvm/IR/Instructions.h"27#include "llvm/IR/IntrinsicInst.h"28#include "llvm/IR/LLVMContext.h"29#include "llvm/IR/Module.h"30#include "llvm/IR/Verifier.h"31#include "llvm/Support/SourceMgr.h"32#include "llvm/Transforms/Utils/ValueMapper.h"33#include "gtest/gtest.h"34 35using namespace llvm;36 37namespace {38 39class CloneInstruction : public ::testing::Test {40protected:41 void SetUp() override { V = nullptr; }42 43 template <typename T>44 T *clone(T *V1) {45 Value *V2 = V1->clone();46 Orig.insert(V1);47 Clones.insert(V2);48 return cast<T>(V2);49 }50 51 void eraseClones() {52 for (Value *V : Clones)53 V->deleteValue();54 Clones.clear();55 }56 57 void TearDown() override {58 eraseClones();59 for (Value *V : Orig)60 V->deleteValue();61 Orig.clear();62 if (V)63 V->deleteValue();64 }65 66 SmallPtrSet<Value *, 4> Orig; // Erase on exit67 SmallPtrSet<Value *, 4> Clones; // Erase in eraseClones68 69 LLVMContext context;70 Value *V;71};72 73TEST_F(CloneInstruction, OverflowBits) {74 V = new Argument(Type::getInt32Ty(context));75 76 BinaryOperator *Add = BinaryOperator::Create(Instruction::Add, V, V);77 BinaryOperator *Sub = BinaryOperator::Create(Instruction::Sub, V, V);78 BinaryOperator *Mul = BinaryOperator::Create(Instruction::Mul, V, V);79 80 BinaryOperator *AddClone = this->clone(Add);81 BinaryOperator *SubClone = this->clone(Sub);82 BinaryOperator *MulClone = this->clone(Mul);83 84 EXPECT_FALSE(AddClone->hasNoUnsignedWrap());85 EXPECT_FALSE(AddClone->hasNoSignedWrap());86 EXPECT_FALSE(SubClone->hasNoUnsignedWrap());87 EXPECT_FALSE(SubClone->hasNoSignedWrap());88 EXPECT_FALSE(MulClone->hasNoUnsignedWrap());89 EXPECT_FALSE(MulClone->hasNoSignedWrap());90 91 eraseClones();92 93 Add->setHasNoUnsignedWrap();94 Sub->setHasNoUnsignedWrap();95 Mul->setHasNoUnsignedWrap();96 97 AddClone = this->clone(Add);98 SubClone = this->clone(Sub);99 MulClone = this->clone(Mul);100 101 EXPECT_TRUE(AddClone->hasNoUnsignedWrap());102 EXPECT_FALSE(AddClone->hasNoSignedWrap());103 EXPECT_TRUE(SubClone->hasNoUnsignedWrap());104 EXPECT_FALSE(SubClone->hasNoSignedWrap());105 EXPECT_TRUE(MulClone->hasNoUnsignedWrap());106 EXPECT_FALSE(MulClone->hasNoSignedWrap());107 108 eraseClones();109 110 Add->setHasNoSignedWrap();111 Sub->setHasNoSignedWrap();112 Mul->setHasNoSignedWrap();113 114 AddClone = this->clone(Add);115 SubClone = this->clone(Sub);116 MulClone = this->clone(Mul);117 118 EXPECT_TRUE(AddClone->hasNoUnsignedWrap());119 EXPECT_TRUE(AddClone->hasNoSignedWrap());120 EXPECT_TRUE(SubClone->hasNoUnsignedWrap());121 EXPECT_TRUE(SubClone->hasNoSignedWrap());122 EXPECT_TRUE(MulClone->hasNoUnsignedWrap());123 EXPECT_TRUE(MulClone->hasNoSignedWrap());124 125 eraseClones();126 127 Add->setHasNoUnsignedWrap(false);128 Sub->setHasNoUnsignedWrap(false);129 Mul->setHasNoUnsignedWrap(false);130 131 AddClone = this->clone(Add);132 SubClone = this->clone(Sub);133 MulClone = this->clone(Mul);134 135 EXPECT_FALSE(AddClone->hasNoUnsignedWrap());136 EXPECT_TRUE(AddClone->hasNoSignedWrap());137 EXPECT_FALSE(SubClone->hasNoUnsignedWrap());138 EXPECT_TRUE(SubClone->hasNoSignedWrap());139 EXPECT_FALSE(MulClone->hasNoUnsignedWrap());140 EXPECT_TRUE(MulClone->hasNoSignedWrap());141}142 143TEST_F(CloneInstruction, Inbounds) {144 V = new Argument(PointerType::get(context, 0));145 146 Constant *Z = Constant::getNullValue(Type::getInt32Ty(context));147 std::vector<Value *> ops;148 ops.push_back(Z);149 GetElementPtrInst *GEP =150 GetElementPtrInst::Create(Type::getInt32Ty(context), V, ops);151 EXPECT_FALSE(this->clone(GEP)->isInBounds());152 153 GEP->setIsInBounds();154 EXPECT_TRUE(this->clone(GEP)->isInBounds());155}156 157TEST_F(CloneInstruction, Exact) {158 V = new Argument(Type::getInt32Ty(context));159 160 BinaryOperator *SDiv = BinaryOperator::Create(Instruction::SDiv, V, V);161 EXPECT_FALSE(this->clone(SDiv)->isExact());162 163 SDiv->setIsExact(true);164 EXPECT_TRUE(this->clone(SDiv)->isExact());165}166 167TEST_F(CloneInstruction, Attributes) {168 Type *ArgTy1[] = {PointerType::get(context, 0)};169 FunctionType *FT1 =170 FunctionType::get(Type::getVoidTy(context), ArgTy1, false);171 172 Function *F1 = Function::Create(FT1, Function::ExternalLinkage);173 BasicBlock *BB = BasicBlock::Create(context, "", F1);174 IRBuilder<> Builder(BB);175 Builder.CreateRetVoid();176 177 Function *F2 = Function::Create(FT1, Function::ExternalLinkage);178 179 Argument *A = &*F1->arg_begin();180 A->addAttr(181 Attribute::getWithCaptureInfo(A->getContext(), CaptureInfo::none()));182 183 SmallVector<ReturnInst*, 4> Returns;184 ValueToValueMapTy VMap;185 VMap[A] = UndefValue::get(A->getType());186 187 CloneFunctionInto(F2, F1, VMap, CloneFunctionChangeType::LocalChangesOnly,188 Returns);189 EXPECT_FALSE(F2->arg_begin()->hasNoCaptureAttr());190 191 delete F1;192 delete F2;193}194 195TEST_F(CloneInstruction, CallingConvention) {196 Type *ArgTy1[] = {PointerType::get(context, 0)};197 FunctionType *FT1 =198 FunctionType::get(Type::getVoidTy(context), ArgTy1, false);199 200 Function *F1 = Function::Create(FT1, Function::ExternalLinkage);201 F1->setCallingConv(CallingConv::Cold);202 BasicBlock *BB = BasicBlock::Create(context, "", F1);203 IRBuilder<> Builder(BB);204 Builder.CreateRetVoid();205 206 Function *F2 = Function::Create(FT1, Function::ExternalLinkage);207 208 SmallVector<ReturnInst*, 4> Returns;209 ValueToValueMapTy VMap;210 VMap[&*F1->arg_begin()] = &*F2->arg_begin();211 212 CloneFunctionInto(F2, F1, VMap, CloneFunctionChangeType::LocalChangesOnly,213 Returns);214 EXPECT_EQ(CallingConv::Cold, F2->getCallingConv());215 216 delete F1;217 delete F2;218}219 220TEST_F(CloneInstruction, DuplicateInstructionsToSplit) {221 Type *ArgTy1[] = {PointerType::get(context, 0)};222 FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);223 V = new Argument(Type::getInt32Ty(context));224 225 Function *F = Function::Create(FT, Function::ExternalLinkage);226 227 BasicBlock *BB1 = BasicBlock::Create(context, "", F);228 IRBuilder<> Builder1(BB1);229 230 BasicBlock *BB2 = BasicBlock::Create(context, "", F);231 IRBuilder<> Builder2(BB2);232 233 Builder1.CreateBr(BB2);234 235 Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));236 Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));237 Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));238 Builder2.CreateRetVoid();239 240 // Dummy DTU.241 ValueToValueMapTy Mapping;242 DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);243 auto Split =244 DuplicateInstructionsInSplitBetween(BB2, BB1, SubInst, Mapping, DTU);245 246 EXPECT_TRUE(Split);247 EXPECT_EQ(Mapping.size(), 2u);248 EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());249 EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());250 251 auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);252 EXPECT_TRUE(AddSplit);253 EXPECT_EQ(AddSplit->getOperand(0), V);254 EXPECT_EQ(AddSplit->getOperand(1), V);255 EXPECT_EQ(AddSplit->getParent(), Split);256 257 auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);258 EXPECT_TRUE(MulSplit);259 EXPECT_EQ(MulSplit->getOperand(0), AddSplit);260 EXPECT_EQ(MulSplit->getOperand(1), V);261 EXPECT_EQ(MulSplit->getParent(), Split);262 263 EXPECT_EQ(AddSplit->getNextNode(), MulSplit);264 EXPECT_EQ(MulSplit->getNextNode(), Split->getTerminator());265 266 delete F;267}268 269TEST_F(CloneInstruction, DuplicateInstructionsToSplitBlocksEq1) {270 Type *ArgTy1[] = {PointerType::get(context, 0)};271 FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);272 V = new Argument(Type::getInt32Ty(context));273 274 Function *F = Function::Create(FT, Function::ExternalLinkage);275 276 BasicBlock *BB1 = BasicBlock::Create(context, "", F);277 IRBuilder<> Builder1(BB1);278 279 BasicBlock *BB2 = BasicBlock::Create(context, "", F);280 IRBuilder<> Builder2(BB2);281 282 Builder1.CreateBr(BB2);283 284 Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));285 Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));286 Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));287 Builder2.CreateBr(BB2);288 289 // Dummy DTU.290 DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);291 ValueToValueMapTy Mapping;292 auto Split = DuplicateInstructionsInSplitBetween(293 BB2, BB2, BB2->getTerminator(), Mapping, DTU);294 295 EXPECT_TRUE(Split);296 EXPECT_EQ(Mapping.size(), 3u);297 EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());298 EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());299 EXPECT_TRUE(Mapping.find(SubInst) != Mapping.end());300 301 auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);302 EXPECT_TRUE(AddSplit);303 EXPECT_EQ(AddSplit->getOperand(0), V);304 EXPECT_EQ(AddSplit->getOperand(1), V);305 EXPECT_EQ(AddSplit->getParent(), Split);306 307 auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);308 EXPECT_TRUE(MulSplit);309 EXPECT_EQ(MulSplit->getOperand(0), AddSplit);310 EXPECT_EQ(MulSplit->getOperand(1), V);311 EXPECT_EQ(MulSplit->getParent(), Split);312 313 auto SubSplit = dyn_cast<Instruction>(Mapping[SubInst]);314 EXPECT_EQ(MulSplit->getNextNode(), SubSplit);315 EXPECT_EQ(SubSplit->getNextNode(), Split->getTerminator());316 EXPECT_EQ(Split->getSingleSuccessor(), BB2);317 EXPECT_EQ(BB2->getSingleSuccessor(), Split);318 319 delete F;320}321 322TEST_F(CloneInstruction, DuplicateInstructionsToSplitBlocksEq2) {323 Type *ArgTy1[] = {PointerType::get(context, 0)};324 FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);325 V = new Argument(Type::getInt32Ty(context));326 327 Function *F = Function::Create(FT, Function::ExternalLinkage);328 329 BasicBlock *BB1 = BasicBlock::Create(context, "", F);330 IRBuilder<> Builder1(BB1);331 332 BasicBlock *BB2 = BasicBlock::Create(context, "", F);333 IRBuilder<> Builder2(BB2);334 335 Builder1.CreateBr(BB2);336 337 Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));338 Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));339 Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));340 Builder2.CreateBr(BB2);341 342 // Dummy DTU.343 DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);344 ValueToValueMapTy Mapping;345 auto Split =346 DuplicateInstructionsInSplitBetween(BB2, BB2, SubInst, Mapping, DTU);347 348 EXPECT_TRUE(Split);349 EXPECT_EQ(Mapping.size(), 2u);350 EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());351 EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());352 353 auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);354 EXPECT_TRUE(AddSplit);355 EXPECT_EQ(AddSplit->getOperand(0), V);356 EXPECT_EQ(AddSplit->getOperand(1), V);357 EXPECT_EQ(AddSplit->getParent(), Split);358 359 auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);360 EXPECT_TRUE(MulSplit);361 EXPECT_EQ(MulSplit->getOperand(0), AddSplit);362 EXPECT_EQ(MulSplit->getOperand(1), V);363 EXPECT_EQ(MulSplit->getParent(), Split);364 EXPECT_EQ(MulSplit->getNextNode(), Split->getTerminator());365 EXPECT_EQ(Split->getSingleSuccessor(), BB2);366 EXPECT_EQ(BB2->getSingleSuccessor(), Split);367 368 delete F;369}370 371static void runWithLoopInfoAndDominatorTree(372 Module &M, StringRef FuncName,373 function_ref<void(Function &F, LoopInfo &LI, DominatorTree &DT)> Test) {374 auto *F = M.getFunction(FuncName);375 ASSERT_NE(F, nullptr) << "Could not find " << FuncName;376 377 DominatorTree DT(*F);378 LoopInfo LI(DT);379 380 Test(*F, LI, DT);381}382 383static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {384 SMDiagnostic Err;385 std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);386 if (!Mod)387 Err.print("CloneLoop", errs());388 return Mod;389}390 391TEST(CloneLoop, CloneLoopNest) {392 // Parse the module.393 LLVMContext Context;394 395 std::unique_ptr<Module> M = parseIR(396 Context,397 R"(define void @foo(ptr %A, i32 %ub) {398entry:399 %guardcmp = icmp slt i32 0, %ub400 br i1 %guardcmp, label %for.outer.preheader, label %for.end401for.outer.preheader:402 br label %for.outer403for.outer:404 %j = phi i32 [ 0, %for.outer.preheader ], [ %inc.outer, %for.outer.latch ]405 br i1 %guardcmp, label %for.inner.preheader, label %for.outer.latch406for.inner.preheader:407 br label %for.inner408for.inner:409 %i = phi i32 [ 0, %for.inner.preheader ], [ %inc, %for.inner ]410 %idxprom = sext i32 %i to i64411 %arrayidx = getelementptr inbounds i32, ptr %A, i64 %idxprom412 store i32 %i, ptr %arrayidx, align 4413 %inc = add nsw i32 %i, 1414 %cmp = icmp slt i32 %inc, %ub415 br i1 %cmp, label %for.inner, label %for.inner.exit416for.inner.exit:417 br label %for.outer.latch418for.outer.latch:419 %inc.outer = add nsw i32 %j, 1420 %cmp.outer = icmp slt i32 %inc.outer, %ub421 br i1 %cmp.outer, label %for.outer, label %for.outer.exit422for.outer.exit:423 br label %for.end424for.end:425 ret void426})"427 );428 429 runWithLoopInfoAndDominatorTree(430 *M, "foo", [&](Function &F, LoopInfo &LI, DominatorTree &DT) {431 Function::iterator FI = F.begin();432 // First basic block is entry - skip it.433 BasicBlock *Preheader = &*(++FI);434 BasicBlock *Header = &*(++FI);435 assert(Header->getName() == "for.outer");436 Loop *L = LI.getLoopFor(Header);437 EXPECT_NE(L, nullptr);438 EXPECT_EQ(Header, L->getHeader());439 EXPECT_EQ(Preheader, L->getLoopPreheader());440 441 ValueToValueMapTy VMap;442 SmallVector<BasicBlock *, 4> ClonedLoopBlocks;443 Loop *NewLoop = cloneLoopWithPreheader(Preheader, Preheader, L, VMap,444 "", &LI, &DT, ClonedLoopBlocks);445 EXPECT_NE(NewLoop, nullptr);446 EXPECT_EQ(NewLoop->getSubLoops().size(), 1u);447 Loop::block_iterator BI = NewLoop->block_begin();448 EXPECT_TRUE((*BI)->getName().starts_with("for.outer"));449 EXPECT_TRUE((*(++BI))->getName().starts_with("for.inner.preheader"));450 EXPECT_TRUE((*(++BI))->getName().starts_with("for.inner"));451 EXPECT_TRUE((*(++BI))->getName().starts_with("for.inner.exit"));452 EXPECT_TRUE((*(++BI))->getName().starts_with("for.outer.latch"));453 });454}455 456class CloneFunc : public ::testing::Test {457protected:458 void SetUp() override {459 SetupModule();460 CreateOldFunc();461 CreateNewFunc();462 SetupFinder();463 }464 465 void TearDown() override { delete Finder; }466 467 void SetupModule() {468 M = new Module("", C);469 }470 471 void CreateOldFunc() {472 FunctionType* FuncType = FunctionType::get(Type::getVoidTy(C), false);473 OldFunc = Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", M);474 CreateOldFunctionBodyAndDI();475 }476 477 void CreateOldFunctionBodyAndDI() {478 DIBuilder DBuilder(*M);479 IRBuilder<> IBuilder(C);480 481 // Function DI482 auto *File = DBuilder.createFile("filename.c", "/file/dir/");483 DITypeRefArray ParamTypes = DBuilder.getOrCreateTypeArray({});484 DISubroutineType *FuncType =485 DBuilder.createSubroutineType(ParamTypes);486 auto *CU = DBuilder.createCompileUnit(487 DISourceLanguageName(dwarf::DW_LANG_C99),488 DBuilder.createFile("filename.c", "/file/dir"), "CloneFunc", false, "",489 0);490 491 auto *Subprogram = DBuilder.createFunction(492 CU, "f", "f", File, 4, FuncType, 3, DINode::FlagZero,493 DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);494 OldFunc->setSubprogram(Subprogram);495 496 // Function body497 BasicBlock* Entry = BasicBlock::Create(C, "", OldFunc);498 IBuilder.SetInsertPoint(Entry);499 DebugLoc Loc = DILocation::get(Subprogram->getContext(), 3, 2, Subprogram);500 IBuilder.SetCurrentDebugLocation(Loc);501 AllocaInst* Alloca = IBuilder.CreateAlloca(IntegerType::getInt32Ty(C));502 IBuilder.SetCurrentDebugLocation(503 DILocation::get(Subprogram->getContext(), 4, 2, Subprogram));504 Value* AllocaContent = IBuilder.getInt32(1);505 Instruction* Store = IBuilder.CreateStore(AllocaContent, Alloca);506 IBuilder.SetCurrentDebugLocation(507 DILocation::get(Subprogram->getContext(), 5, 2, Subprogram));508 509 // Create a local variable around the alloca510 auto *IntType = DBuilder.createBasicType("int", 32, dwarf::DW_ATE_signed);511 auto *E = DBuilder.createExpression();512 auto *Variable =513 DBuilder.createAutoVariable(Subprogram, "x", File, 5, IntType, true);514 auto *DL = DILocation::get(Subprogram->getContext(), 5, 0, Subprogram);515 DBuilder.insertDeclare(Alloca, Variable, E, DL, Store->getIterator());516 DBuilder.insertDbgValueIntrinsic(AllocaContent, Variable, E, DL, Entry);517 // Also create an inlined variable.518 // Create a distinct struct type that we should not duplicate during519 // cloning).520 auto *StructType = DICompositeType::getDistinct(521 C, dwarf::DW_TAG_structure_type, "some_struct", nullptr, 0, nullptr,522 nullptr, 32, 32, 0, DINode::FlagZero, nullptr, 0, std::nullopt, nullptr,523 nullptr);524 auto *InlinedSP = DBuilder.createFunction(525 CU, "inlined", "inlined", File, 8, FuncType, 9, DINode::FlagZero,526 DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);527 auto *InlinedVar =528 DBuilder.createAutoVariable(InlinedSP, "inlined", File, 5, StructType, true);529 auto *Scope = DBuilder.createLexicalBlock(530 DBuilder.createLexicalBlockFile(InlinedSP, File), File, 1, 1);531 auto InlinedDL = DILocation::get(532 Subprogram->getContext(), 9, 4, Scope,533 DILocation::get(Subprogram->getContext(), 5, 2, Subprogram));534 IBuilder.SetCurrentDebugLocation(InlinedDL);535 DBuilder.insertDeclare(Alloca, InlinedVar, E, InlinedDL,536 Store->getIterator());537 IBuilder.CreateStore(IBuilder.getInt32(2), Alloca);538 // Finalize the debug info.539 DBuilder.finalize();540 IBuilder.CreateRetVoid();541 542 // Create another, empty, compile unit.543 DIBuilder DBuilder2(*M);544 DBuilder2.createCompileUnit(DISourceLanguageName(dwarf::DW_LANG_C99),545 DBuilder.createFile("extra.c", "/file/dir"),546 "CloneFunc", false, "", 0);547 DBuilder2.finalize();548 }549 550 void CreateNewFunc() {551 ValueToValueMapTy VMap;552 NewFunc = CloneFunction(OldFunc, VMap, nullptr);553 }554 555 void SetupFinder() {556 Finder = new DebugInfoFinder();557 Finder->processModule(*M);558 }559 560 LLVMContext C;561 Function* OldFunc;562 Function* NewFunc;563 Module* M;564 DebugInfoFinder* Finder;565};566 567// Test that a new, distinct function was created.568TEST_F(CloneFunc, NewFunctionCreated) {569 EXPECT_NE(OldFunc, NewFunc);570}571 572// Test that a new subprogram entry was added and is pointing to the new573// function, while the original subprogram still points to the old one.574TEST_F(CloneFunc, Subprogram) {575 EXPECT_FALSE(verifyModule(*M, &errs()));576 EXPECT_EQ(3U, Finder->subprogram_count());577 EXPECT_NE(NewFunc->getSubprogram(), OldFunc->getSubprogram());578}579 580// Test that instructions in the old function still belong to it in the581// metadata, while instruction in the new function belong to the new one.582TEST_F(CloneFunc, InstructionOwnership) {583 EXPECT_FALSE(verifyModule(*M));584 585 inst_iterator OldIter = inst_begin(OldFunc);586 inst_iterator OldEnd = inst_end(OldFunc);587 inst_iterator NewIter = inst_begin(NewFunc);588 inst_iterator NewEnd = inst_end(NewFunc);589 while (OldIter != OldEnd && NewIter != NewEnd) {590 Instruction& OldI = *OldIter;591 Instruction& NewI = *NewIter;592 EXPECT_NE(&OldI, &NewI);593 594 EXPECT_EQ(OldI.hasMetadata(), NewI.hasMetadata());595 if (OldI.hasMetadata()) {596 const DebugLoc& OldDL = OldI.getDebugLoc();597 const DebugLoc& NewDL = NewI.getDebugLoc();598 599 // Verify that the debug location data is the same600 EXPECT_EQ(OldDL.getLine(), NewDL.getLine());601 EXPECT_EQ(OldDL.getCol(), NewDL.getCol());602 603 // But that they belong to different functions604 auto *OldSubprogram = cast<DISubprogram>(OldDL.getInlinedAtScope());605 auto *NewSubprogram = cast<DISubprogram>(NewDL.getInlinedAtScope());606 EXPECT_EQ(OldFunc->getSubprogram(), OldSubprogram);607 EXPECT_EQ(NewFunc->getSubprogram(), NewSubprogram);608 }609 610 ++OldIter;611 ++NewIter;612 }613 EXPECT_EQ(OldEnd, OldIter);614 EXPECT_EQ(NewEnd, NewIter);615}616 617// Test that the arguments for debug intrinsics in the new function were618// properly cloned619TEST_F(CloneFunc, DebugIntrinsics) {620 EXPECT_FALSE(verifyModule(*M));621 622 inst_iterator OldIter = inst_begin(OldFunc);623 inst_iterator OldEnd = inst_end(OldFunc);624 inst_iterator NewIter = inst_begin(NewFunc);625 inst_iterator NewEnd = inst_end(NewFunc);626 while (OldIter != OldEnd && NewIter != NewEnd) {627 Instruction& OldI = *OldIter;628 Instruction& NewI = *NewIter;629 if (DbgDeclareInst* OldIntrin = dyn_cast<DbgDeclareInst>(&OldI)) {630 DbgDeclareInst* NewIntrin = dyn_cast<DbgDeclareInst>(&NewI);631 EXPECT_TRUE(NewIntrin);632 633 // Old address must belong to the old function634 EXPECT_EQ(OldFunc, cast<AllocaInst>(OldIntrin->getAddress())->635 getParent()->getParent());636 // New address must belong to the new function637 EXPECT_EQ(NewFunc, cast<AllocaInst>(NewIntrin->getAddress())->638 getParent()->getParent());639 640 if (OldIntrin->getDebugLoc()->getInlinedAt()) {641 // Inlined variable should refer to the same DILocalVariable as in the642 // Old Function643 EXPECT_EQ(OldIntrin->getVariable(), NewIntrin->getVariable());644 } else {645 // Old variable must belong to the old function.646 EXPECT_EQ(OldFunc->getSubprogram(),647 cast<DISubprogram>(OldIntrin->getVariable()->getScope()));648 // New variable must belong to the new function.649 EXPECT_EQ(NewFunc->getSubprogram(),650 cast<DISubprogram>(NewIntrin->getVariable()->getScope()));651 }652 } else if (DbgValueInst* OldIntrin = dyn_cast<DbgValueInst>(&OldI)) {653 DbgValueInst* NewIntrin = dyn_cast<DbgValueInst>(&NewI);654 EXPECT_TRUE(NewIntrin);655 656 if (!OldIntrin->getDebugLoc()->getInlinedAt()) {657 // Old variable must belong to the old function.658 EXPECT_EQ(OldFunc->getSubprogram(),659 cast<DISubprogram>(OldIntrin->getVariable()->getScope()));660 // New variable must belong to the new function.661 EXPECT_EQ(NewFunc->getSubprogram(),662 cast<DISubprogram>(NewIntrin->getVariable()->getScope()));663 }664 }665 666 ++OldIter;667 ++NewIter;668 }669}670 671static int GetDICompileUnitCount(const Module& M) {672 if (const auto* LLVM_DBG_CU = M.getNamedMetadata("llvm.dbg.cu")) {673 return LLVM_DBG_CU->getNumOperands();674 }675 return 0;676}677 678static bool haveCompileUnitsInCommon(const Module &LHS, const Module &RHS) {679 const NamedMDNode *LHSCUs = LHS.getNamedMetadata("llvm.dbg.cu");680 if (!LHSCUs)681 return false;682 683 const NamedMDNode *RHSCUs = RHS.getNamedMetadata("llvm.dbg.cu");684 if (!RHSCUs)685 return false;686 687 SmallPtrSet<const MDNode *, 8> Found;688 for (int I = 0, E = LHSCUs->getNumOperands(); I != E; ++I)689 if (const MDNode *N = LHSCUs->getOperand(I))690 Found.insert(N);691 692 for (int I = 0, E = RHSCUs->getNumOperands(); I != E; ++I)693 if (const MDNode *N = RHSCUs->getOperand(I))694 if (Found.count(N))695 return true;696 697 return false;698}699 700TEST(CloneFunction, CloneEmptyFunction) {701 StringRef ImplAssembly = R"(702 define void @foo() {703 ret void704 }705 declare void @bar()706 )";707 708 LLVMContext Context;709 SMDiagnostic Error;710 711 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);712 EXPECT_TRUE(ImplModule != nullptr);713 auto *ImplFunction = ImplModule->getFunction("foo");714 EXPECT_TRUE(ImplFunction != nullptr);715 auto *DeclFunction = ImplModule->getFunction("bar");716 EXPECT_TRUE(DeclFunction != nullptr);717 718 ValueToValueMapTy VMap;719 SmallVector<ReturnInst *, 8> Returns;720 ClonedCodeInfo CCI;721 CloneFunctionInto(ImplFunction, DeclFunction, VMap,722 CloneFunctionChangeType::GlobalChanges, Returns, "", &CCI);723 724 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));725 EXPECT_FALSE(CCI.ContainsCalls);726 EXPECT_FALSE(CCI.ContainsDynamicAllocas);727}728 729TEST(CloneFunction, CloneFunctionWithInalloca) {730 StringRef ImplAssembly = R"(731 declare void @a(ptr inalloca(i32))732 define void @foo() {733 %a = alloca inalloca i32734 call void @a(ptr inalloca(i32) %a)735 ret void736 }737 declare void @bar()738 )";739 740 LLVMContext Context;741 SMDiagnostic Error;742 743 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);744 EXPECT_TRUE(ImplModule != nullptr);745 auto *ImplFunction = ImplModule->getFunction("foo");746 EXPECT_TRUE(ImplFunction != nullptr);747 auto *DeclFunction = ImplModule->getFunction("bar");748 EXPECT_TRUE(DeclFunction != nullptr);749 750 ValueToValueMapTy VMap;751 SmallVector<ReturnInst *, 8> Returns;752 ClonedCodeInfo CCI;753 CloneFunctionInto(DeclFunction, ImplFunction, VMap,754 CloneFunctionChangeType::GlobalChanges, Returns, "", &CCI);755 756 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));757 EXPECT_TRUE(CCI.ContainsCalls);758 EXPECT_TRUE(CCI.ContainsDynamicAllocas);759}760 761TEST(CloneFunction, CloneFunctionWithSubprograms) {762 // Tests that the debug info is duplicated correctly when a DISubprogram763 // happens to be one of the operands of the DISubprogram that is being cloned.764 // In general, operands of "test" that are distinct should be duplicated,765 // but in this case "my_operator" should not be duplicated. If it is766 // duplicated, the metadata in the llvm.dbg.declare could end up with767 // different duplicates.768 StringRef ImplAssembly = R"(769 declare void @llvm.dbg.declare(metadata, metadata, metadata)770 771 define void @test() !dbg !5 {772 call void @llvm.dbg.declare(metadata i8* undef, metadata !4, metadata !DIExpression()), !dbg !6773 ret void774 }775 776 declare void @cloned()777 778 !llvm.dbg.cu = !{!0}779 !llvm.module.flags = !{!2}780 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1)781 !1 = !DIFile(filename: "test.cpp", directory: "")782 !2 = !{i32 1, !"Debug Info Version", i32 3}783 !3 = distinct !DISubprogram(name: "my_operator", scope: !1, unit: !0, retainedNodes: !{!4})784 !4 = !DILocalVariable(name: "awaitables", scope: !3)785 !5 = distinct !DISubprogram(name: "test", scope: !3, unit: !0)786 !6 = !DILocation(line: 55, column: 15, scope: !3, inlinedAt: !7)787 !7 = distinct !DILocation(line: 73, column: 14, scope: !5)788 )";789 790 LLVMContext Context;791 SMDiagnostic Error;792 793 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);794 EXPECT_TRUE(ImplModule != nullptr);795 auto *OldFunc = ImplModule->getFunction("test");796 EXPECT_TRUE(OldFunc != nullptr);797 auto *NewFunc = ImplModule->getFunction("cloned");798 EXPECT_TRUE(NewFunc != nullptr);799 800 ValueToValueMapTy VMap;801 SmallVector<ReturnInst *, 8> Returns;802 ClonedCodeInfo CCI;803 CloneFunctionInto(NewFunc, OldFunc, VMap,804 CloneFunctionChangeType::GlobalChanges, Returns, "", &CCI);805 806 // This fails if the scopes in the llvm.dbg.declare variable and location807 // aren't the same.808 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));809}810 811TEST(CloneFunction, CloneFunctionWithInlinedSubprograms) {812 StringRef ImplAssembly = R"(813 declare void @llvm.dbg.declare(metadata, metadata, metadata)814 815 define void @test() !dbg !3 {816 call void @llvm.dbg.declare(metadata i8* undef, metadata !5, metadata !DIExpression()), !dbg !7817 ret void818 }819 820 declare void @cloned()821 822 !llvm.dbg.cu = !{!0}823 !llvm.module.flags = !{!2}824 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1)825 !1 = !DIFile(filename: "test.cpp", directory: "")826 !2 = !{i32 1, !"Debug Info Version", i32 3}827 !3 = distinct !DISubprogram(name: "test", scope: !0, unit: !0)828 !4 = distinct !DISubprogram(name: "inlined", scope: !0, unit: !0, retainedNodes: !{!5})829 !5 = !DILocalVariable(name: "awaitables", scope: !4)830 !6 = distinct !DILexicalBlock(scope: !4, file: !1, line: 1)831 !7 = !DILocation(line: 1, scope: !6, inlinedAt: !8)832 !8 = !DILocation(line: 10, scope: !3)833 )";834 835 LLVMContext Context;836 SMDiagnostic Error;837 838 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);839 EXPECT_TRUE(ImplModule != nullptr);840 auto *Func = ImplModule->getFunction("test");841 EXPECT_TRUE(Func != nullptr);842 auto *ClonedFunc = ImplModule->getFunction("cloned");843 EXPECT_TRUE(ClonedFunc != nullptr);844 845 ValueToValueMapTy VMap;846 SmallVector<ReturnInst *, 8> Returns;847 ClonedCodeInfo CCI;848 CloneFunctionInto(ClonedFunc, Func, VMap,849 CloneFunctionChangeType::GlobalChanges, Returns, "", &CCI);850 851 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));852 853 // Check that DILexicalBlock of inlined function was not cloned.854 auto DbgDeclareI = Func->begin()->begin()->getDbgRecordRange().begin();855 auto ClonedDbgDeclareI =856 ClonedFunc->begin()->begin()->getDbgRecordRange().begin();857 const DebugLoc &DbgLoc = DbgDeclareI->getDebugLoc();858 const DebugLoc &ClonedDbgLoc = ClonedDbgDeclareI->getDebugLoc();859 EXPECT_NE(DbgLoc.get(), ClonedDbgLoc.get());860 EXPECT_EQ(cast<DILexicalBlock>(DbgLoc.getScope()),861 cast<DILexicalBlock>(ClonedDbgLoc.getScope()));862}863 864TEST(CloneFunction, CloneFunctionToDifferentModule) {865 StringRef ImplAssembly = R"(866 define void @foo() {867 ret void, !dbg !5868 }869 870 !llvm.module.flags = !{!0}871 !llvm.dbg.cu = !{!2, !6}872 !0 = !{i32 1, !"Debug Info Version", i32 3}873 !1 = distinct !DISubprogram(unit: !2)874 !2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3)875 !3 = !DIFile(filename: "foo.c", directory: "/tmp")876 !4 = distinct !DISubprogram(unit: !2)877 !5 = !DILocation(line: 4, scope: !1)878 !6 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3)879 )";880 StringRef DeclAssembly = R"(881 declare void @foo()882 )";883 884 LLVMContext Context;885 SMDiagnostic Error;886 887 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);888 EXPECT_TRUE(ImplModule != nullptr);889 // DICompileUnits: !2, !6. Only !2 is reachable from @foo().890 EXPECT_TRUE(GetDICompileUnitCount(*ImplModule) == 2);891 auto* ImplFunction = ImplModule->getFunction("foo");892 EXPECT_TRUE(ImplFunction != nullptr);893 894 auto DeclModule = parseAssemblyString(DeclAssembly, Error, Context);895 EXPECT_TRUE(DeclModule != nullptr);896 // No DICompileUnits defined here.897 EXPECT_TRUE(GetDICompileUnitCount(*DeclModule) == 0);898 auto* DeclFunction = DeclModule->getFunction("foo");899 EXPECT_TRUE(DeclFunction != nullptr);900 901 ValueToValueMapTy VMap;902 VMap[ImplFunction] = DeclFunction;903 // No args to map904 SmallVector<ReturnInst*, 8> Returns;905 CloneFunctionInto(DeclFunction, ImplFunction, VMap,906 CloneFunctionChangeType::DifferentModule, Returns);907 908 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));909 EXPECT_FALSE(verifyModule(*DeclModule, &errs()));910 // DICompileUnit !2 shall be cloned into DeclModule.911 EXPECT_TRUE(GetDICompileUnitCount(*DeclModule) == 1);912 EXPECT_FALSE(haveCompileUnitsInCommon(*ImplModule, *DeclModule));913}914 915class CloneModule : public ::testing::Test {916protected:917 void SetUp() override {918 SetupModule();919 CreateOldModule();920 CreateNewModule();921 }922 923 void SetupModule() { OldM = new Module("", C); }924 925 void CreateOldModule() {926 auto *CD = OldM->getOrInsertComdat("comdat");927 CD->setSelectionKind(Comdat::ExactMatch);928 929 auto GV = new GlobalVariable(930 *OldM, Type::getInt32Ty(C), false, GlobalValue::ExternalLinkage,931 ConstantInt::get(Type::getInt32Ty(C), 1), "gv");932 GV->addMetadata(LLVMContext::MD_type, *MDNode::get(C, {}));933 GV->setComdat(CD);934 935 // Add ifuncs936 {937 const unsigned AddrSpace = 123;938 auto *FuncPtrTy = PointerType::get(C, AddrSpace);939 auto *FuncTy = FunctionType::get(FuncPtrTy, false);940 941 auto *ResolverF = Function::Create(FuncTy, GlobalValue::PrivateLinkage,942 AddrSpace, "resolver", OldM);943 BasicBlock *ResolverBody = BasicBlock::Create(C, "", ResolverF);944 ReturnInst::Create(C, ConstantPointerNull::get(FuncPtrTy), ResolverBody);945 946 GlobalIFunc *GI = GlobalIFunc::create(FuncTy, AddrSpace,947 GlobalValue::LinkOnceODRLinkage,948 "an_ifunc", ResolverF, OldM);949 GI->setVisibility(GlobalValue::ProtectedVisibility);950 }951 952 {953 // Add an empty compile unit first that isn't otherwise referenced, to954 // confirm that compile units get cloned in the correct order.955 DIBuilder EmptyBuilder(*OldM);956 auto *File = EmptyBuilder.createFile("empty.c", "/file/dir/");957 (void)EmptyBuilder.createCompileUnit(958 DISourceLanguageName(dwarf::DW_LANG_C99), File, "EmptyUnit", false,959 "", 0);960 EmptyBuilder.finalize();961 }962 963 DIBuilder DBuilder(*OldM);964 IRBuilder<> IBuilder(C);965 966 auto *FuncType = FunctionType::get(Type::getVoidTy(C), false);967 auto *PersFn = Function::Create(FuncType, GlobalValue::ExternalLinkage,968 "persfn", OldM);969 auto *F =970 Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", OldM);971 F->setPersonalityFn(PersFn);972 F->setComdat(CD);973 974 // Create debug info975 auto *File = DBuilder.createFile("filename.c", "/file/dir/");976 DITypeRefArray ParamTypes = DBuilder.getOrCreateTypeArray({});977 DISubroutineType *DFuncType = DBuilder.createSubroutineType(ParamTypes);978 auto *CU = DBuilder.createCompileUnit(979 DISourceLanguageName(dwarf::DW_LANG_C99),980 DBuilder.createFile("filename.c", "/file/dir"), "CloneModule", false,981 "", 0);982 // Function DI983 auto *Subprogram = DBuilder.createFunction(984 CU, "f", "f", File, 4, DFuncType, 3, DINode::FlagZero,985 DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);986 F->setSubprogram(Subprogram);987 988 // Create and assign DIGlobalVariableExpression to gv989 auto GVExpression = DBuilder.createGlobalVariableExpression(990 Subprogram, "gv", "gv", File, 1, DBuilder.createNullPtrType(), false);991 GV->addDebugInfo(GVExpression);992 993 // DIGlobalVariableExpression not attached to any global variable994 auto Expr = DBuilder.createExpression(995 ArrayRef<uint64_t>{dwarf::DW_OP_constu, 42U, dwarf::DW_OP_stack_value});996 997 DBuilder.createGlobalVariableExpression(998 Subprogram, "unattached", "unattached", File, 1,999 DBuilder.createNullPtrType(), false, true, Expr);1000 1001 auto *Entry = BasicBlock::Create(C, "", F);1002 IBuilder.SetInsertPoint(Entry);1003 IBuilder.CreateRetVoid();1004 1005 auto *G =1006 Function::Create(FuncType, GlobalValue::ExternalLinkage, "g", OldM);1007 G->addMetadata(LLVMContext::MD_type, *MDNode::get(C, {}));1008 1009 auto *NonEntryBlock = BasicBlock::Create(C, "", F);1010 IBuilder.SetInsertPoint(NonEntryBlock);1011 IBuilder.CreateRetVoid();1012 1013 // Create a global that contains the block address in its initializer.1014 auto *BlockAddress = BlockAddress::get(NonEntryBlock);1015 new GlobalVariable(*OldM, BlockAddress->getType(), /*isConstant=*/true,1016 GlobalVariable::ExternalLinkage, BlockAddress,1017 "blockaddr");1018 1019 // Finalize the debug info1020 DBuilder.finalize();1021 }1022 1023 void CreateNewModule() { NewM = llvm::CloneModule(*OldM).release(); }1024 1025 LLVMContext C;1026 Module *OldM;1027 Module *NewM;1028};1029 1030TEST_F(CloneModule, Verify) {1031 // Confirm the old module is (still) valid.1032 EXPECT_FALSE(verifyModule(*OldM, &errs()));1033 1034 // Check the new module.1035 EXPECT_FALSE(verifyModule(*NewM, &errs()));1036}1037 1038TEST_F(CloneModule, OldModuleUnchanged) {1039 DebugInfoFinder Finder;1040 Finder.processModule(*OldM);1041 EXPECT_EQ(1U, Finder.subprogram_count());1042}1043 1044TEST_F(CloneModule, Subprogram) {1045 Function *NewF = NewM->getFunction("f");1046 DISubprogram *SP = NewF->getSubprogram();1047 EXPECT_TRUE(SP != nullptr);1048 EXPECT_EQ(SP->getName(), "f");1049 EXPECT_EQ(SP->getFile()->getFilename(), "filename.c");1050 EXPECT_EQ(SP->getLine(), (unsigned)4);1051}1052 1053TEST_F(CloneModule, FunctionDeclarationMetadata) {1054 Function *NewF = NewM->getFunction("g");1055 EXPECT_NE(nullptr, NewF->getMetadata(LLVMContext::MD_type));1056}1057 1058TEST_F(CloneModule, GlobalMetadata) {1059 GlobalVariable *NewGV = NewM->getGlobalVariable("gv");1060 EXPECT_NE(nullptr, NewGV->getMetadata(LLVMContext::MD_type));1061}1062 1063TEST_F(CloneModule, GlobalDebugInfo) {1064 GlobalVariable *NewGV = NewM->getGlobalVariable("gv");1065 EXPECT_TRUE(NewGV != nullptr);1066 1067 // Find debug info expression assigned to global1068 SmallVector<DIGlobalVariableExpression *, 1> GVs;1069 NewGV->getDebugInfo(GVs);1070 EXPECT_EQ(GVs.size(), 1U);1071 1072 DIGlobalVariableExpression *GVExpr = GVs[0];1073 DIGlobalVariable *GV = GVExpr->getVariable();1074 EXPECT_TRUE(GV != nullptr);1075 1076 EXPECT_EQ(GV->getName(), "gv");1077 EXPECT_EQ(GV->getLine(), 1U);1078 1079 // Assert that the scope of the debug info attached to1080 // global variable matches the cloned function.1081 DISubprogram *SP = NewM->getFunction("f")->getSubprogram();1082 EXPECT_TRUE(SP != nullptr);1083 EXPECT_EQ(GV->getScope(), SP);1084}1085 1086TEST_F(CloneModule, CompileUnit) {1087 // Find DICompileUnit listed in llvm.dbg.cu1088 auto *NMD = NewM->getNamedMetadata("llvm.dbg.cu");1089 EXPECT_TRUE(NMD != nullptr);1090 EXPECT_EQ(NMD->getNumOperands(), 2U);1091 EXPECT_FALSE(haveCompileUnitsInCommon(*OldM, *NewM));1092 1093 // Check that the empty CU is first, even though it's not referenced except1094 // from named metadata.1095 DICompileUnit *EmptyCU = dyn_cast<llvm::DICompileUnit>(NMD->getOperand(0));1096 EXPECT_TRUE(EmptyCU != nullptr);1097 EXPECT_EQ("EmptyUnit", EmptyCU->getProducer());1098 1099 // Get the interesting CU.1100 DICompileUnit *CU = dyn_cast<llvm::DICompileUnit>(NMD->getOperand(1));1101 EXPECT_TRUE(CU != nullptr);1102 EXPECT_EQ("CloneModule", CU->getProducer());1103 1104 // Assert this CU is consistent with the cloned function debug info1105 DISubprogram *SP = NewM->getFunction("f")->getSubprogram();1106 EXPECT_TRUE(SP != nullptr);1107 EXPECT_EQ(SP->getUnit(), CU);1108 1109 // Check globals listed in CU have the correct scope1110 DIGlobalVariableExpressionArray GlobalArray = CU->getGlobalVariables();1111 EXPECT_EQ(GlobalArray.size(), 2U);1112 for (DIGlobalVariableExpression *GVExpr : GlobalArray) {1113 DIGlobalVariable *GV = GVExpr->getVariable();1114 EXPECT_EQ(GV->getScope(), SP);1115 }1116}1117 1118TEST_F(CloneModule, Comdat) {1119 GlobalVariable *NewGV = NewM->getGlobalVariable("gv");1120 auto *CD = NewGV->getComdat();1121 ASSERT_NE(nullptr, CD);1122 EXPECT_EQ("comdat", CD->getName());1123 EXPECT_EQ(Comdat::ExactMatch, CD->getSelectionKind());1124 1125 Function *NewF = NewM->getFunction("f");1126 EXPECT_EQ(CD, NewF->getComdat());1127}1128 1129TEST_F(CloneModule, IFunc) {1130 ASSERT_EQ(1u, NewM->ifunc_size());1131 1132 const GlobalIFunc &IFunc = *NewM->ifunc_begin();1133 EXPECT_EQ("an_ifunc", IFunc.getName());1134 EXPECT_EQ(GlobalValue::LinkOnceODRLinkage, IFunc.getLinkage());1135 EXPECT_EQ(GlobalValue::ProtectedVisibility, IFunc.getVisibility());1136 EXPECT_EQ(123u, IFunc.getAddressSpace());1137 1138 const Function *Resolver = IFunc.getResolverFunction();1139 ASSERT_NE(nullptr, Resolver);1140 EXPECT_EQ("resolver", Resolver->getName());1141 EXPECT_EQ(GlobalValue::PrivateLinkage, Resolver->getLinkage());1142}1143 1144TEST_F(CloneModule, CloneDbgLabel) {1145 LLVMContext Context;1146 1147 std::unique_ptr<Module> M = parseIR(Context,1148 R"M(1149define void @noop(ptr nocapture noundef writeonly align 4 %dst) local_unnamed_addr !dbg !3 {1150entry:1151 %call = tail call spir_func i64 @foo(i32 noundef 0)1152 #dbg_label(!11, !12)1153 store i64 %call, ptr %dst, align 41154 ret void1155}1156 1157declare i64 @foo(i32 noundef) local_unnamed_addr1158 1159!llvm.dbg.cu = !{!0}1160!llvm.module.flags = !{!2}1161 1162!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 19.0.0git", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)1163!1 = !DIFile(filename: "<stdin>", directory: "foo")1164!2 = !{i32 2, !"Debug Info Version", i32 3}1165!3 = distinct !DISubprogram(name: "noop", scope: !4, file: !4, line: 17, type: !5, scopeLine: 17, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !9)1166!4 = !DIFile(filename: "file", directory: "foo")1167!5 = !DISubroutineType(types: !6)1168!6 = !{null, !7}1169!7 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !8, size: 64)1170!8 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)1171!9 = !{}1172!11 = !DILabel(scope: !3, name: "foo", file: !4, line: 23)1173!12 = !DILocation(line: 23, scope: !3)1174)M");1175 1176 ASSERT_FALSE(verifyModule(*M, &errs()));1177 auto NewM = llvm::CloneModule(*M);1178 EXPECT_FALSE(verifyModule(*NewM, &errs()));1179}1180 1181TEST_F(CloneInstruction, cloneKeyInstructions) {1182 LLVMContext Context;1183 1184 std::unique_ptr<Module> M = parseIR(Context, R"(1185 define void @test(ptr align 4 %dst) !dbg !3 {1186 store i64 1, ptr %dst, align 4, !dbg !61187 store i64 2, ptr %dst, align 4, !dbg !71188 store i64 3, ptr %dst, align 4, !dbg !81189 ret void, !dbg !91190 }1191 1192 !llvm.dbg.cu = !{!0}1193 !llvm.module.flags = !{!2}1194 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1)1195 !1 = !DIFile(filename: "test.cpp", directory: "")1196 !2 = !{i32 1, !"Debug Info Version", i32 3}1197 !3 = distinct !DISubprogram(name: "test", scope: !0, unit: !0, keyInstructions: true)1198 !4 = distinct !DISubprogram(name: "inlined", scope: !0, unit: !0, retainedNodes: !{!5}, keyInstructions: true)1199 !5 = !DILocalVariable(name: "awaitables", scope: !4)1200 !6 = !DILocation(line: 1, scope: !4, inlinedAt: !8, atomGroup: 1, atomRank: 1)1201 !7 = !DILocation(line: 2, scope: !3, atomGroup: 1, atomRank: 1)1202 !8 = !DILocation(line: 3, scope: !3, atomGroup: 1, atomRank: 1)1203 !9 = !DILocation(line: 4, scope: !3, atomGroup: 2, atomRank: 1)1204 )");1205 1206 ASSERT_FALSE(verifyModule(*M, &errs()));1207 1208#define EXPECT_ATOM(Inst, G) \1209 EXPECT_TRUE(Inst->getDebugLoc()); \1210 EXPECT_EQ(Inst->getDebugLoc()->getAtomGroup(), uint64_t(G));1211 1212 Function *F = M->getFunction("test");1213 BasicBlock *BB = &*F->begin();1214 ASSERT_TRUE(F);1215 Instruction *Store1 = &*BB->begin();1216 Instruction *Store2 = Store1->getNextNode();1217 Instruction *Store3 = Store2->getNextNode();1218 Instruction *Ret = Store3->getNextNode();1219 1220 // Test the remapping works as expected outside of cloning.1221 ValueToValueMapTy VM;1222 // Store1 and Store2 have the same atomGroup number, but have different1223 // inlining scopes, so only Store1 should change group.1224 mapAtomInstance(Store1->getDebugLoc(), VM);1225 for (Instruction &I : *BB)1226 RemapSourceAtom(&I, VM);1227 EXPECT_ATOM(Store1, 3);1228 EXPECT_ATOM(Store2, 1);1229 EXPECT_ATOM(Store3, 1);1230 EXPECT_ATOM(Ret, 2);1231 VM.clear();1232 1233 // Store2 and Store3 have the same group number; both should get remapped.1234 mapAtomInstance(Store2->getDebugLoc(), VM);1235 for (Instruction &I : *BB)1236 RemapSourceAtom(&I, VM);1237 EXPECT_ATOM(Store1, 3);1238 EXPECT_ATOM(Store2, 4);1239 EXPECT_ATOM(Store3, 4);1240 EXPECT_ATOM(Ret, 2);1241 VM.clear();1242 1243 // Cloning BB with MapAtoms=false should clone the atom numbers.1244 BasicBlock *BB2 =1245 CloneBasicBlock(BB, VM, "", nullptr, nullptr, /*MapAtoms*/ false);1246 for (Instruction &I : *BB2)1247 RemapSourceAtom(&I, VM);1248 Store1 = &*BB2->begin();1249 Store2 = Store1->getNextNode();1250 Store3 = Store2->getNextNode();1251 Ret = Store3->getNextNode();1252 EXPECT_ATOM(Store1, 3);1253 EXPECT_ATOM(Store2, 4);1254 EXPECT_ATOM(Store3, 4);1255 EXPECT_ATOM(Ret, 2);1256 VM.clear();1257 delete BB2;1258 1259 // Cloning BB with MapAtoms=true should map the atom numbers.1260 BasicBlock *BB3 =1261 CloneBasicBlock(BB, VM, "", nullptr, nullptr, /*MapAtoms*/ true);1262 for (Instruction &I : *BB3)1263 RemapSourceAtom(&I, VM);1264 Store1 = &*BB3->begin();1265 Store2 = Store1->getNextNode();1266 Store3 = Store2->getNextNode();1267 Ret = Store3->getNextNode();1268 EXPECT_ATOM(Store1, 5);1269 EXPECT_ATOM(Store2, 6);1270 EXPECT_ATOM(Store3, 6);1271 EXPECT_ATOM(Ret, 7);1272 VM.clear();1273 delete BB3;1274#undef EXPECT_ATOM1275}1276 1277// Checks that block addresses in global initializers are properly cloned.1278TEST_F(CloneModule, GlobalWithBlockAddressesInitializer) {1279 auto *OriginalBa = cast<BlockAddress>(1280 OldM->getGlobalVariable("blockaddr")->getInitializer());1281 auto *ClonedBa = cast<BlockAddress>(1282 NewM->getGlobalVariable("blockaddr")->getInitializer());1283 ASSERT_NE(OriginalBa->getBasicBlock(), ClonedBa->getBasicBlock());1284}1285 1286} // namespace1287