1 //===- ModuleUtilsTest.cpp - Unit tests for Module utility ----===// 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/Transforms/Utils/ModuleUtils.h" 10 #include "llvm/ADT/StringRef.h" 11 #include "llvm/AsmParser/Parser.h" 12 #include "llvm/IR/LLVMContext.h" 13 #include "llvm/IR/Module.h" 14 #include "llvm/Support/SourceMgr.h" 15 #include "gtest/gtest.h" 16 17 using namespace llvm; 18 19 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) { 20 SMDiagnostic Err; 21 std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C); 22 if (!Mod) 23 Err.print("ModuleUtilsTest", errs()); 24 return Mod; 25 } 26 27 static int getUsedListSize(Module &M, StringRef Name) { 28 auto *UsedList = M.getGlobalVariable(Name); 29 if (!UsedList) 30 return 0; 31 auto *UsedListBaseArrayType = 32 cast<ArrayType>(UsedList->getType()->getElementType()); 33 return UsedListBaseArrayType->getNumElements(); 34 } 35 36 TEST(ModuleUtils, AppendToUsedList1) { 37 LLVMContext C; 38 39 std::unique_ptr<Module> M = parseIR( 40 C, R"(@x = addrspace(4) global [2 x i32] zeroinitializer, align 4)"); 41 SmallVector<GlobalValue *, 2> Globals; 42 for (auto &G : M->globals()) { 43 Globals.push_back(&G); 44 } 45 EXPECT_EQ(0, getUsedListSize(*M, "llvm.compiler.used")); 46 appendToCompilerUsed(*M, Globals); 47 EXPECT_EQ(1, getUsedListSize(*M, "llvm.compiler.used")); 48 49 EXPECT_EQ(0, getUsedListSize(*M, "llvm.used")); 50 appendToUsed(*M, Globals); 51 EXPECT_EQ(1, getUsedListSize(*M, "llvm.used")); 52 } 53 54 TEST(ModuleUtils, AppendToUsedList2) { 55 LLVMContext C; 56 57 std::unique_ptr<Module> M = 58 parseIR(C, R"(@x = global [2 x i32] zeroinitializer, align 4)"); 59 SmallVector<GlobalValue *, 2> Globals; 60 for (auto &G : M->globals()) { 61 Globals.push_back(&G); 62 } 63 EXPECT_EQ(0, getUsedListSize(*M, "llvm.compiler.used")); 64 appendToCompilerUsed(*M, Globals); 65 EXPECT_EQ(1, getUsedListSize(*M, "llvm.compiler.used")); 66 67 EXPECT_EQ(0, getUsedListSize(*M, "llvm.used")); 68 appendToUsed(*M, Globals); 69 EXPECT_EQ(1, getUsedListSize(*M, "llvm.used")); 70 } 71