xref: /llvm-project/llvm/lib/Transforms/Utils/ModuleUtils.cpp (revision e7cd42f8e4da1beed52f401dcf87d22d36a2c81c)
1 //===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
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 // This family of functions perform manipulations on Modules.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Utils/ModuleUtils.h"
14 #include "llvm/Analysis/VectorUtils.h"
15 #include "llvm/IR/DerivedTypes.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/MDBuilder.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Support/xxhash.h"
22 using namespace llvm;
23 
24 #define DEBUG_TYPE "moduleutils"
25 
26 static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F,
27                                 int Priority, Constant *Data) {
28   IRBuilder<> IRB(M.getContext());
29   FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);
30 
31   // Get the current set of static global constructors and add the new ctor
32   // to the list.
33   SmallVector<Constant *, 16> CurrentCtors;
34   StructType *EltTy = StructType::get(
35       IRB.getInt32Ty(), PointerType::get(FnTy, F->getAddressSpace()),
36       IRB.getInt8PtrTy());
37 
38   if (GlobalVariable *GVCtor = M.getNamedGlobal(ArrayName)) {
39     if (Constant *Init = GVCtor->getInitializer()) {
40       unsigned n = Init->getNumOperands();
41       CurrentCtors.reserve(n + 1);
42       for (unsigned i = 0; i != n; ++i)
43         CurrentCtors.push_back(cast<Constant>(Init->getOperand(i)));
44     }
45     GVCtor->eraseFromParent();
46   }
47 
48   // Build a 3 field global_ctor entry.  We don't take a comdat key.
49   Constant *CSVals[3];
50   CSVals[0] = IRB.getInt32(Priority);
51   CSVals[1] = F;
52   CSVals[2] = Data ? ConstantExpr::getPointerCast(Data, IRB.getInt8PtrTy())
53                    : Constant::getNullValue(IRB.getInt8PtrTy());
54   Constant *RuntimeCtorInit =
55       ConstantStruct::get(EltTy, ArrayRef(CSVals, EltTy->getNumElements()));
56 
57   CurrentCtors.push_back(RuntimeCtorInit);
58 
59   // Create a new initializer.
60   ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
61   Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
62 
63   // Create the new global variable and replace all uses of
64   // the old global variable with the new one.
65   (void)new GlobalVariable(M, NewInit->getType(), false,
66                            GlobalValue::AppendingLinkage, NewInit, ArrayName);
67 }
68 
69 void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data) {
70   appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
71 }
72 
73 void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data) {
74   appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data);
75 }
76 
77 static void collectUsedGlobals(GlobalVariable *GV,
78                                SmallSetVector<Constant *, 16> &Init) {
79   if (!GV || !GV->hasInitializer())
80     return;
81 
82   auto *CA = cast<ConstantArray>(GV->getInitializer());
83   for (Use &Op : CA->operands())
84     Init.insert(cast<Constant>(Op));
85 }
86 
87 static void appendToUsedList(Module &M, StringRef Name, ArrayRef<GlobalValue *> Values) {
88   GlobalVariable *GV = M.getGlobalVariable(Name);
89 
90   SmallSetVector<Constant *, 16> Init;
91   collectUsedGlobals(GV, Init);
92   if (GV)
93     GV->eraseFromParent();
94 
95   Type *ArrayEltTy = llvm::Type::getInt8PtrTy(M.getContext());
96   for (auto *V : Values)
97     Init.insert(ConstantExpr::getPointerBitCastOrAddrSpaceCast(V, ArrayEltTy));
98 
99   if (Init.empty())
100     return;
101 
102   ArrayType *ATy = ArrayType::get(ArrayEltTy, Init.size());
103   GV = new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
104                                 ConstantArray::get(ATy, Init.getArrayRef()),
105                                 Name);
106   GV->setSection("llvm.metadata");
107 }
108 
109 void llvm::appendToUsed(Module &M, ArrayRef<GlobalValue *> Values) {
110   appendToUsedList(M, "llvm.used", Values);
111 }
112 
113 void llvm::appendToCompilerUsed(Module &M, ArrayRef<GlobalValue *> Values) {
114   appendToUsedList(M, "llvm.compiler.used", Values);
115 }
116 
117 static void removeFromUsedList(Module &M, StringRef Name,
118                                function_ref<bool(Constant *)> ShouldRemove) {
119   GlobalVariable *GV = M.getNamedGlobal(Name);
120   if (!GV)
121     return;
122 
123   SmallSetVector<Constant *, 16> Init;
124   collectUsedGlobals(GV, Init);
125 
126   Type *ArrayEltTy = cast<ArrayType>(GV->getValueType())->getElementType();
127 
128   SmallVector<Constant *, 16> NewInit;
129   for (Constant *MaybeRemoved : Init) {
130     if (!ShouldRemove(MaybeRemoved->stripPointerCasts()))
131       NewInit.push_back(MaybeRemoved);
132   }
133 
134   if (!NewInit.empty()) {
135     ArrayType *ATy = ArrayType::get(ArrayEltTy, NewInit.size());
136     GlobalVariable *NewGV =
137         new GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
138                            ConstantArray::get(ATy, NewInit), "", GV,
139                            GV->getThreadLocalMode(), GV->getAddressSpace());
140     NewGV->setSection(GV->getSection());
141     NewGV->takeName(GV);
142   }
143 
144   GV->eraseFromParent();
145 }
146 
147 void llvm::removeFromUsedLists(Module &M,
148                                function_ref<bool(Constant *)> ShouldRemove) {
149   removeFromUsedList(M, "llvm.used", ShouldRemove);
150   removeFromUsedList(M, "llvm.compiler.used", ShouldRemove);
151 }
152 
153 void llvm::setKCFIType(Module &M, Function &F, StringRef MangledType) {
154   if (!M.getModuleFlag("kcfi"))
155     return;
156   // Matches CodeGenModule::CreateKCFITypeId in Clang.
157   LLVMContext &Ctx = M.getContext();
158   MDBuilder MDB(Ctx);
159   F.setMetadata(
160       LLVMContext::MD_kcfi_type,
161       MDNode::get(Ctx, MDB.createConstant(ConstantInt::get(
162                            Type::getInt32Ty(Ctx),
163                            static_cast<uint32_t>(xxHash64(MangledType))))));
164   // If the module was compiled with -fpatchable-function-entry, ensure
165   // we use the same patchable-function-prefix.
166   if (auto *MD = mdconst::extract_or_null<ConstantInt>(
167           M.getModuleFlag("kcfi-offset"))) {
168     if (unsigned Offset = MD->getZExtValue())
169       F.addFnAttr("patchable-function-prefix", std::to_string(Offset));
170   }
171 }
172 
173 FunctionCallee
174 llvm::declareSanitizerInitFunction(Module &M, StringRef InitName,
175                                    ArrayRef<Type *> InitArgTypes) {
176   assert(!InitName.empty() && "Expected init function name");
177   return M.getOrInsertFunction(
178       InitName,
179       FunctionType::get(Type::getVoidTy(M.getContext()), InitArgTypes, false),
180       AttributeList());
181 }
182 
183 Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
184   Function *Ctor = Function::createWithDefaultAttr(
185       FunctionType::get(Type::getVoidTy(M.getContext()), false),
186       GlobalValue::InternalLinkage, M.getDataLayout().getProgramAddressSpace(),
187       CtorName, &M);
188   Ctor->addFnAttr(Attribute::NoUnwind);
189   setKCFIType(M, *Ctor, "_ZTSFvvE"); // void (*)(void)
190   BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
191   ReturnInst::Create(M.getContext(), CtorBB);
192   // Ensure Ctor cannot be discarded, even if in a comdat.
193   appendToUsed(M, {Ctor});
194   return Ctor;
195 }
196 
197 std::pair<Function *, FunctionCallee> llvm::createSanitizerCtorAndInitFunctions(
198     Module &M, StringRef CtorName, StringRef InitName,
199     ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
200     StringRef VersionCheckName) {
201   assert(!InitName.empty() && "Expected init function name");
202   assert(InitArgs.size() == InitArgTypes.size() &&
203          "Sanitizer's init function expects different number of arguments");
204   FunctionCallee InitFunction =
205       declareSanitizerInitFunction(M, InitName, InitArgTypes);
206   Function *Ctor = createSanitizerCtor(M, CtorName);
207   IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
208   IRB.CreateCall(InitFunction, InitArgs);
209   if (!VersionCheckName.empty()) {
210     FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
211         VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
212         AttributeList());
213     IRB.CreateCall(VersionCheckFunction, {});
214   }
215   return std::make_pair(Ctor, InitFunction);
216 }
217 
218 std::pair<Function *, FunctionCallee>
219 llvm::getOrCreateSanitizerCtorAndInitFunctions(
220     Module &M, StringRef CtorName, StringRef InitName,
221     ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
222     function_ref<void(Function *, FunctionCallee)> FunctionsCreatedCallback,
223     StringRef VersionCheckName) {
224   assert(!CtorName.empty() && "Expected ctor function name");
225 
226   if (Function *Ctor = M.getFunction(CtorName))
227     // FIXME: Sink this logic into the module, similar to the handling of
228     // globals. This will make moving to a concurrent model much easier.
229     if (Ctor->arg_empty() ||
230         Ctor->getReturnType() == Type::getVoidTy(M.getContext()))
231       return {Ctor, declareSanitizerInitFunction(M, InitName, InitArgTypes)};
232 
233   Function *Ctor;
234   FunctionCallee InitFunction;
235   std::tie(Ctor, InitFunction) = llvm::createSanitizerCtorAndInitFunctions(
236       M, CtorName, InitName, InitArgTypes, InitArgs, VersionCheckName);
237   FunctionsCreatedCallback(Ctor, InitFunction);
238   return std::make_pair(Ctor, InitFunction);
239 }
240 
241 void llvm::filterDeadComdatFunctions(
242     SmallVectorImpl<Function *> &DeadComdatFunctions) {
243   SmallPtrSet<Function *, 32> MaybeDeadFunctions;
244   SmallPtrSet<Comdat *, 32> MaybeDeadComdats;
245   for (Function *F : DeadComdatFunctions) {
246     MaybeDeadFunctions.insert(F);
247     if (Comdat *C = F->getComdat())
248       MaybeDeadComdats.insert(C);
249   }
250 
251   // Find comdats for which all users are dead now.
252   SmallPtrSet<Comdat *, 32> DeadComdats;
253   for (Comdat *C : MaybeDeadComdats) {
254     auto IsUserDead = [&](GlobalObject *GO) {
255       auto *F = dyn_cast<Function>(GO);
256       return F && MaybeDeadFunctions.contains(F);
257     };
258     if (all_of(C->getUsers(), IsUserDead))
259       DeadComdats.insert(C);
260   }
261 
262   // Only keep functions which have no comdat or a dead comdat.
263   erase_if(DeadComdatFunctions, [&](Function *F) {
264     Comdat *C = F->getComdat();
265     return C && !DeadComdats.contains(C);
266   });
267 }
268 
269 std::string llvm::getUniqueModuleId(Module *M) {
270   MD5 Md5;
271   bool ExportsSymbols = false;
272   auto AddGlobal = [&](GlobalValue &GV) {
273     if (GV.isDeclaration() || GV.getName().startswith("llvm.") ||
274         !GV.hasExternalLinkage() || GV.hasComdat())
275       return;
276     ExportsSymbols = true;
277     Md5.update(GV.getName());
278     Md5.update(ArrayRef<uint8_t>{0});
279   };
280 
281   for (auto &F : *M)
282     AddGlobal(F);
283   for (auto &GV : M->globals())
284     AddGlobal(GV);
285   for (auto &GA : M->aliases())
286     AddGlobal(GA);
287   for (auto &IF : M->ifuncs())
288     AddGlobal(IF);
289 
290   if (!ExportsSymbols)
291     return "";
292 
293   MD5::MD5Result R;
294   Md5.final(R);
295 
296   SmallString<32> Str;
297   MD5::stringifyResult(R, Str);
298   return ("." + Str).str();
299 }
300 
301 void VFABI::setVectorVariantNames(CallInst *CI,
302                                   ArrayRef<std::string> VariantMappings) {
303   if (VariantMappings.empty())
304     return;
305 
306   SmallString<256> Buffer;
307   llvm::raw_svector_ostream Out(Buffer);
308   for (const std::string &VariantMapping : VariantMappings)
309     Out << VariantMapping << ",";
310   // Get rid of the trailing ','.
311   assert(!Buffer.str().empty() && "Must have at least one char.");
312   Buffer.pop_back();
313 
314   Module *M = CI->getModule();
315 #ifndef NDEBUG
316   for (const std::string &VariantMapping : VariantMappings) {
317     LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << VariantMapping << "'\n");
318     std::optional<VFInfo> VI = VFABI::tryDemangleForVFABI(VariantMapping, *M);
319     assert(VI && "Cannot add an invalid VFABI name.");
320     assert(M->getNamedValue(VI->VectorName) &&
321            "Cannot add variant to attribute: "
322            "vector function declaration is missing.");
323   }
324 #endif
325   CI->addFnAttr(
326       Attribute::get(M->getContext(), MappingsAttrName, Buffer.str()));
327 }
328 
329 void llvm::embedBufferInModule(Module &M, MemoryBufferRef Buf,
330                                StringRef SectionName, Align Alignment) {
331   // Embed the memory buffer into the module.
332   Constant *ModuleConstant = ConstantDataArray::get(
333       M.getContext(), ArrayRef(Buf.getBufferStart(), Buf.getBufferSize()));
334   GlobalVariable *GV = new GlobalVariable(
335       M, ModuleConstant->getType(), true, GlobalValue::PrivateLinkage,
336       ModuleConstant, "llvm.embedded.object");
337   GV->setSection(SectionName);
338   GV->setAlignment(Alignment);
339 
340   LLVMContext &Ctx = M.getContext();
341   NamedMDNode *MD = M.getOrInsertNamedMetadata("llvm.embedded.objects");
342   Metadata *MDVals[] = {ConstantAsMetadata::get(GV),
343                         MDString::get(Ctx, SectionName)};
344 
345   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
346   GV->setMetadata(LLVMContext::MD_exclude, llvm::MDNode::get(Ctx, {}));
347 
348   appendToCompilerUsed(M, GV);
349 }
350 
351 bool llvm::lowerGlobalIFuncUsersAsGlobalCtor(
352     Module &M, ArrayRef<GlobalIFunc *> FilteredIFuncsToLower) {
353   SmallVector<GlobalIFunc *, 32> AllIFuncs;
354   ArrayRef<GlobalIFunc *> IFuncsToLower = FilteredIFuncsToLower;
355   if (FilteredIFuncsToLower.empty()) { // Default to lowering all ifuncs
356     for (GlobalIFunc &GI : M.ifuncs())
357       AllIFuncs.push_back(&GI);
358     IFuncsToLower = AllIFuncs;
359   }
360 
361   bool UnhandledUsers = false;
362   LLVMContext &Ctx = M.getContext();
363   const DataLayout &DL = M.getDataLayout();
364 
365   PointerType *TableEntryTy =
366       Ctx.supportsTypedPointers()
367           ? PointerType::get(Type::getInt8Ty(Ctx), DL.getProgramAddressSpace())
368           : PointerType::get(Ctx, DL.getProgramAddressSpace());
369 
370   ArrayType *FuncPtrTableTy =
371       ArrayType::get(TableEntryTy, IFuncsToLower.size());
372 
373   Align PtrAlign = DL.getABITypeAlign(TableEntryTy);
374 
375   // Create a global table of function pointers we'll initialize in a global
376   // constructor.
377   auto *FuncPtrTable = new GlobalVariable(
378       M, FuncPtrTableTy, false, GlobalValue::InternalLinkage,
379       PoisonValue::get(FuncPtrTableTy), "", nullptr,
380       GlobalVariable::NotThreadLocal, DL.getDefaultGlobalsAddressSpace());
381   FuncPtrTable->setAlignment(PtrAlign);
382 
383   // Create a function to initialize the function pointer table.
384   Function *NewCtor = Function::Create(
385       FunctionType::get(Type::getVoidTy(Ctx), false), Function::InternalLinkage,
386       DL.getProgramAddressSpace(), "", &M);
387 
388   BasicBlock *BB = BasicBlock::Create(Ctx, "", NewCtor);
389   IRBuilder<> InitBuilder(BB);
390 
391   size_t TableIndex = 0;
392   for (GlobalIFunc *GI : IFuncsToLower) {
393     Function *ResolvedFunction = GI->getResolverFunction();
394 
395     // We don't know what to pass to a resolver function taking arguments
396     //
397     // FIXME: Is this even valid? clang and gcc don't complain but this
398     // probably should be invalid IR. We could just pass through undef.
399     if (!std::empty(ResolvedFunction->getFunctionType()->params())) {
400       LLVM_DEBUG(dbgs() << "Not lowering ifunc resolver function "
401                         << ResolvedFunction->getName() << " with parameters\n");
402       UnhandledUsers = true;
403       continue;
404     }
405 
406     // Initialize the function pointer table.
407     CallInst *ResolvedFunc = InitBuilder.CreateCall(ResolvedFunction);
408     Value *Casted = InitBuilder.CreatePointerCast(ResolvedFunc, TableEntryTy);
409     Constant *GEP = cast<Constant>(InitBuilder.CreateConstInBoundsGEP2_32(
410         FuncPtrTableTy, FuncPtrTable, 0, TableIndex++));
411     InitBuilder.CreateAlignedStore(Casted, GEP, PtrAlign);
412 
413     // Update all users to load a pointer from the global table.
414     for (User *User : make_early_inc_range(GI->users())) {
415       Instruction *UserInst = dyn_cast<Instruction>(User);
416       if (!UserInst) {
417         // TODO: Should handle constantexpr casts in user instructions. Probably
418         // can't do much about constant initializers.
419         UnhandledUsers = true;
420         continue;
421       }
422 
423       IRBuilder<> UseBuilder(UserInst);
424       LoadInst *ResolvedTarget =
425           UseBuilder.CreateAlignedLoad(TableEntryTy, GEP, PtrAlign);
426       Value *ResolvedCast =
427           UseBuilder.CreatePointerCast(ResolvedTarget, GI->getType());
428       UserInst->replaceUsesOfWith(GI, ResolvedCast);
429     }
430 
431     // If we handled all users, erase the ifunc.
432     if (GI->use_empty())
433       GI->eraseFromParent();
434   }
435 
436   InitBuilder.CreateRetVoid();
437 
438   PointerType *ConstantDataTy = Ctx.supportsTypedPointers()
439                                     ? PointerType::get(Type::getInt8Ty(Ctx), 0)
440                                     : PointerType::get(Ctx, 0);
441 
442   // TODO: Is this the right priority? Probably should be before any other
443   // constructors?
444   const int Priority = 10;
445   appendToGlobalCtors(M, NewCtor, Priority,
446                       ConstantPointerNull::get(ConstantDataTy));
447   return UnhandledUsers;
448 }
449