Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/Internalize.cpp
35266 views
//===-- Internalize.cpp - Mark functions internal -------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This pass loops over all of the functions and variables in the input module.9// If the function or variable does not need to be preserved according to the10// client supplied callback, it is marked as internal.11//12// This transformation would not be legal in a regular compilation, but it gets13// extra information from the linker about what is safe.14//15// For example: Internalizing a function with external linkage. Only if we are16// told it is only used from within this module, it is safe to do it.17//18//===----------------------------------------------------------------------===//1920#include "llvm/Transforms/IPO/Internalize.h"21#include "llvm/ADT/SmallString.h"22#include "llvm/ADT/Statistic.h"23#include "llvm/ADT/StringSet.h"24#include "llvm/Analysis/CallGraph.h"25#include "llvm/IR/Module.h"26#include "llvm/Support/CommandLine.h"27#include "llvm/Support/Debug.h"28#include "llvm/Support/GlobPattern.h"29#include "llvm/Support/LineIterator.h"30#include "llvm/Support/MemoryBuffer.h"31#include "llvm/Support/raw_ostream.h"32#include "llvm/TargetParser/Triple.h"33#include "llvm/Transforms/IPO.h"34using namespace llvm;3536#define DEBUG_TYPE "internalize"3738STATISTIC(NumAliases, "Number of aliases internalized");39STATISTIC(NumFunctions, "Number of functions internalized");40STATISTIC(NumGlobals, "Number of global vars internalized");4142// APIFile - A file which contains a list of symbol glob patterns that should43// not be marked external.44static cl::opt<std::string>45APIFile("internalize-public-api-file", cl::value_desc("filename"),46cl::desc("A file containing list of symbol names to preserve"));4748// APIList - A list of symbol glob patterns that should not be marked internal.49static cl::list<std::string>50APIList("internalize-public-api-list", cl::value_desc("list"),51cl::desc("A list of symbol names to preserve"), cl::CommaSeparated);5253namespace {54// Helper to load an API list to preserve from file and expose it as a functor55// for internalization.56class PreserveAPIList {57public:58PreserveAPIList() {59if (!APIFile.empty())60LoadFile(APIFile);61for (StringRef Pattern : APIList)62addGlob(Pattern);63}6465bool operator()(const GlobalValue &GV) {66return llvm::any_of(67ExternalNames, [&](GlobPattern &GP) { return GP.match(GV.getName()); });68}6970private:71// Contains the set of symbols loaded from file72SmallVector<GlobPattern> ExternalNames;7374void addGlob(StringRef Pattern) {75auto GlobOrErr = GlobPattern::create(Pattern);76if (!GlobOrErr) {77errs() << "WARNING: when loading pattern: '"78<< toString(GlobOrErr.takeError()) << "' ignoring";79return;80}81ExternalNames.emplace_back(std::move(*GlobOrErr));82}8384void LoadFile(StringRef Filename) {85// Load the APIFile...86ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =87MemoryBuffer::getFile(Filename);88if (!BufOrErr) {89errs() << "WARNING: Internalize couldn't load file '" << Filename90<< "'! Continuing as if it's empty.\n";91return; // Just continue as if the file were empty92}93Buf = std::move(*BufOrErr);94for (line_iterator I(*Buf, true), E; I != E; ++I)95addGlob(*I);96}9798std::shared_ptr<MemoryBuffer> Buf;99};100} // end anonymous namespace101102bool InternalizePass::shouldPreserveGV(const GlobalValue &GV) {103// Function must be defined here104if (GV.isDeclaration())105return true;106107// Available externally is really just a "declaration with a body".108if (GV.hasAvailableExternallyLinkage())109return true;110111// Assume that dllexported symbols are referenced elsewhere112if (GV.hasDLLExportStorageClass())113return true;114115// As the name suggests, externally initialized variables need preserving as116// they would be initialized elsewhere externally.117if (const auto *G = dyn_cast<GlobalVariable>(&GV))118if (G->isExternallyInitialized())119return true;120121// Already local, has nothing to do.122if (GV.hasLocalLinkage())123return false;124125// Check some special cases126if (AlwaysPreserved.count(GV.getName()))127return true;128129return MustPreserveGV(GV);130}131132bool InternalizePass::maybeInternalize(133GlobalValue &GV, DenseMap<const Comdat *, ComdatInfo> &ComdatMap) {134SmallString<0> ComdatName;135if (Comdat *C = GV.getComdat()) {136// For GlobalAlias, C is the aliasee object's comdat which may have been137// redirected. So ComdatMap may not contain C.138if (ComdatMap.lookup(C).External)139return false;140141if (auto *GO = dyn_cast<GlobalObject>(&GV)) {142// If a comdat with one member is not externally visible, we can drop it.143// Otherwise, the comdat can be used to establish dependencies among the144// group of sections. Thus we have to keep the comdat but switch it to145// nodeduplicate.146// Note: nodeduplicate is not necessary for COFF. wasm doesn't support147// nodeduplicate.148ComdatInfo &Info = ComdatMap.find(C)->second;149if (Info.Size == 1)150GO->setComdat(nullptr);151else if (!IsWasm)152C->setSelectionKind(Comdat::NoDeduplicate);153}154155if (GV.hasLocalLinkage())156return false;157} else {158if (GV.hasLocalLinkage())159return false;160161if (shouldPreserveGV(GV))162return false;163}164165GV.setVisibility(GlobalValue::DefaultVisibility);166GV.setLinkage(GlobalValue::InternalLinkage);167return true;168}169170// If GV is part of a comdat and is externally visible, update the comdat size171// and keep track of its comdat so that we don't internalize any of its members.172void InternalizePass::checkComdat(173GlobalValue &GV, DenseMap<const Comdat *, ComdatInfo> &ComdatMap) {174Comdat *C = GV.getComdat();175if (!C)176return;177178ComdatInfo &Info = ComdatMap.try_emplace(C).first->second;179++Info.Size;180if (shouldPreserveGV(GV))181Info.External = true;182}183184bool InternalizePass::internalizeModule(Module &M) {185bool Changed = false;186187SmallVector<GlobalValue *, 4> Used;188collectUsedGlobalVariables(M, Used, false);189190// Collect comdat size and visiblity information for the module.191DenseMap<const Comdat *, ComdatInfo> ComdatMap;192if (!M.getComdatSymbolTable().empty()) {193for (Function &F : M)194checkComdat(F, ComdatMap);195for (GlobalVariable &GV : M.globals())196checkComdat(GV, ComdatMap);197for (GlobalAlias &GA : M.aliases())198checkComdat(GA, ComdatMap);199}200201// We must assume that globals in llvm.used have a reference that not even202// the linker can see, so we don't internalize them.203// For llvm.compiler.used the situation is a bit fuzzy. The assembler and204// linker can drop those symbols. If this pass is running as part of LTO,205// one might think that it could just drop llvm.compiler.used. The problem206// is that even in LTO llvm doesn't see every reference. For example,207// we don't see references from function local inline assembly. To be208// conservative, we internalize symbols in llvm.compiler.used, but we209// keep llvm.compiler.used so that the symbol is not deleted by llvm.210for (GlobalValue *V : Used) {211AlwaysPreserved.insert(V->getName());212}213214// Never internalize the llvm.used symbol. It is used to implement215// attribute((used)).216// FIXME: Shouldn't this just filter on llvm.metadata section??217AlwaysPreserved.insert("llvm.used");218AlwaysPreserved.insert("llvm.compiler.used");219220// Never internalize anchors used by the machine module info, else the info221// won't find them. (see MachineModuleInfo.)222AlwaysPreserved.insert("llvm.global_ctors");223AlwaysPreserved.insert("llvm.global_dtors");224AlwaysPreserved.insert("llvm.global.annotations");225226// Never internalize symbols code-gen inserts.227// FIXME: We should probably add this (and the __stack_chk_guard) via some228// type of call-back in CodeGen.229AlwaysPreserved.insert("__stack_chk_fail");230if (Triple(M.getTargetTriple()).isOSAIX())231AlwaysPreserved.insert("__ssp_canary_word");232else233AlwaysPreserved.insert("__stack_chk_guard");234235// Mark all functions not in the api as internal.236IsWasm = Triple(M.getTargetTriple()).isOSBinFormatWasm();237for (Function &I : M) {238if (!maybeInternalize(I, ComdatMap))239continue;240Changed = true;241242++NumFunctions;243LLVM_DEBUG(dbgs() << "Internalizing func " << I.getName() << "\n");244}245246// Mark all global variables with initializers that are not in the api as247// internal as well.248for (auto &GV : M.globals()) {249if (!maybeInternalize(GV, ComdatMap))250continue;251Changed = true;252253++NumGlobals;254LLVM_DEBUG(dbgs() << "Internalized gvar " << GV.getName() << "\n");255}256257// Mark all aliases that are not in the api as internal as well.258for (auto &GA : M.aliases()) {259if (!maybeInternalize(GA, ComdatMap))260continue;261Changed = true;262263++NumAliases;264LLVM_DEBUG(dbgs() << "Internalized alias " << GA.getName() << "\n");265}266267return Changed;268}269270InternalizePass::InternalizePass() : MustPreserveGV(PreserveAPIList()) {}271272PreservedAnalyses InternalizePass::run(Module &M, ModuleAnalysisManager &AM) {273if (!internalizeModule(M))274return PreservedAnalyses::all();275276return PreservedAnalyses::none();277}278279280