[InstCombine] Signed saturation patterns
[llvm-core.git] / lib / IR / Module.cpp
blob25efd009194f4374a755fe57138f786febad1a92
1 //===- Module.cpp - Implement the Module class ----------------------------===//
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 file implements the Module class for the IR library.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/Module.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/Comdat.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GVMaterializer.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalIFunc.h"
32 #include "llvm/IR/GlobalValue.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/SymbolTableListTraits.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/TypeFinder.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/ValueSymbolTable.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/Error.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/RandomNumberGenerator.h"
48 #include "llvm/Support/VersionTuple.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <memory>
53 #include <utility>
54 #include <vector>
56 using namespace llvm;
58 //===----------------------------------------------------------------------===//
59 // Methods to implement the globals and functions lists.
62 // Explicit instantiations of SymbolTableListTraits since some of the methods
63 // are not in the public header file.
64 template class llvm::SymbolTableListTraits<Function>;
65 template class llvm::SymbolTableListTraits<GlobalVariable>;
66 template class llvm::SymbolTableListTraits<GlobalAlias>;
67 template class llvm::SymbolTableListTraits<GlobalIFunc>;
69 //===----------------------------------------------------------------------===//
70 // Primitive Module methods.
73 Module::Module(StringRef MID, LLVMContext &C)
74 : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
75 ValSymTab = new ValueSymbolTable();
76 NamedMDSymTab = new StringMap<NamedMDNode *>();
77 Context.addModule(this);
80 Module::~Module() {
81 Context.removeModule(this);
82 dropAllReferences();
83 GlobalList.clear();
84 FunctionList.clear();
85 AliasList.clear();
86 IFuncList.clear();
87 NamedMDList.clear();
88 delete ValSymTab;
89 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
92 std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
93 SmallString<32> Salt(P->getPassName());
95 // This RNG is guaranteed to produce the same random stream only
96 // when the Module ID and thus the input filename is the same. This
97 // might be problematic if the input filename extension changes
98 // (e.g. from .c to .bc or .ll).
100 // We could store this salt in NamedMetadata, but this would make
101 // the parameter non-const. This would unfortunately make this
102 // interface unusable by any Machine passes, since they only have a
103 // const reference to their IR Module. Alternatively we can always
104 // store salt metadata from the Module constructor.
105 Salt += sys::path::filename(getModuleIdentifier());
107 return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
110 /// getNamedValue - Return the first global value in the module with
111 /// the specified name, of arbitrary type. This method returns null
112 /// if a global with the specified name is not found.
113 GlobalValue *Module::getNamedValue(StringRef Name) const {
114 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
117 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
118 /// This ID is uniqued across modules in the current LLVMContext.
119 unsigned Module::getMDKindID(StringRef Name) const {
120 return Context.getMDKindID(Name);
123 /// getMDKindNames - Populate client supplied SmallVector with the name for
124 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
125 /// so it is filled in as an empty string.
126 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
127 return Context.getMDKindNames(Result);
130 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
131 return Context.getOperandBundleTags(Result);
134 //===----------------------------------------------------------------------===//
135 // Methods for easy access to the functions in the module.
138 // getOrInsertFunction - Look up the specified function in the module symbol
139 // table. If it does not exist, add a prototype for the function and return
140 // it. This is nice because it allows most passes to get away with not handling
141 // the symbol table directly for this common task.
143 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
144 AttributeList AttributeList) {
145 // See if we have a definition for the specified function already.
146 GlobalValue *F = getNamedValue(Name);
147 if (!F) {
148 // Nope, add it
149 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
150 DL.getProgramAddressSpace(), Name);
151 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
152 New->setAttributes(AttributeList);
153 FunctionList.push_back(New);
154 return {Ty, New}; // Return the new prototype.
157 // If the function exists but has the wrong type, return a bitcast to the
158 // right type.
159 auto *PTy = PointerType::get(Ty, F->getAddressSpace());
160 if (F->getType() != PTy)
161 return {Ty, ConstantExpr::getBitCast(F, PTy)};
163 // Otherwise, we just found the existing function or a prototype.
164 return {Ty, F};
167 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
168 return getOrInsertFunction(Name, Ty, AttributeList());
171 // getFunction - Look up the specified function in the module symbol table.
172 // If it does not exist, return null.
174 Function *Module::getFunction(StringRef Name) const {
175 return dyn_cast_or_null<Function>(getNamedValue(Name));
178 //===----------------------------------------------------------------------===//
179 // Methods for easy access to the global variables in the module.
182 /// getGlobalVariable - Look up the specified global variable in the module
183 /// symbol table. If it does not exist, return null. The type argument
184 /// should be the underlying type of the global, i.e., it should not have
185 /// the top-level PointerType, which represents the address of the global.
186 /// If AllowLocal is set to true, this function will return types that
187 /// have an local. By default, these types are not returned.
189 GlobalVariable *Module::getGlobalVariable(StringRef Name,
190 bool AllowLocal) const {
191 if (GlobalVariable *Result =
192 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
193 if (AllowLocal || !Result->hasLocalLinkage())
194 return Result;
195 return nullptr;
198 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
199 /// 1. If it does not exist, add a declaration of the global and return it.
200 /// 2. Else, the global exists but has the wrong type: return the function
201 /// with a constantexpr cast to the right type.
202 /// 3. Finally, if the existing global is the correct declaration, return the
203 /// existing global.
204 Constant *Module::getOrInsertGlobal(
205 StringRef Name, Type *Ty,
206 function_ref<GlobalVariable *()> CreateGlobalCallback) {
207 // See if we have a definition for the specified global already.
208 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
209 if (!GV)
210 GV = CreateGlobalCallback();
211 assert(GV && "The CreateGlobalCallback is expected to create a global");
213 // If the variable exists but has the wrong type, return a bitcast to the
214 // right type.
215 Type *GVTy = GV->getType();
216 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
217 if (GVTy != PTy)
218 return ConstantExpr::getBitCast(GV, PTy);
220 // Otherwise, we just found the existing function or a prototype.
221 return GV;
224 // Overload to construct a global variable using its constructor's defaults.
225 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
226 return getOrInsertGlobal(Name, Ty, [&] {
227 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
228 nullptr, Name);
232 //===----------------------------------------------------------------------===//
233 // Methods for easy access to the global variables in the module.
236 // getNamedAlias - Look up the specified global in the module symbol table.
237 // If it does not exist, return null.
239 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
240 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
243 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
244 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
247 /// getNamedMetadata - Return the first NamedMDNode in the module with the
248 /// specified name. This method returns null if a NamedMDNode with the
249 /// specified name is not found.
250 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
251 SmallString<256> NameData;
252 StringRef NameRef = Name.toStringRef(NameData);
253 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
256 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
257 /// with the specified name. This method returns a new NamedMDNode if a
258 /// NamedMDNode with the specified name is not found.
259 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
260 NamedMDNode *&NMD =
261 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
262 if (!NMD) {
263 NMD = new NamedMDNode(Name);
264 NMD->setParent(this);
265 NamedMDList.push_back(NMD);
267 return NMD;
270 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
271 /// delete it.
272 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
273 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
274 NamedMDList.erase(NMD->getIterator());
277 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
278 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
279 uint64_t Val = Behavior->getLimitedValue();
280 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
281 MFB = static_cast<ModFlagBehavior>(Val);
282 return true;
285 return false;
288 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
289 void Module::
290 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
291 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
292 if (!ModFlags) return;
294 for (const MDNode *Flag : ModFlags->operands()) {
295 ModFlagBehavior MFB;
296 if (Flag->getNumOperands() >= 3 &&
297 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
298 dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
299 // Check the operands of the MDNode before accessing the operands.
300 // The verifier will actually catch these failures.
301 MDString *Key = cast<MDString>(Flag->getOperand(1));
302 Metadata *Val = Flag->getOperand(2);
303 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
308 /// Return the corresponding value if Key appears in module flags, otherwise
309 /// return null.
310 Metadata *Module::getModuleFlag(StringRef Key) const {
311 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
312 getModuleFlagsMetadata(ModuleFlags);
313 for (const ModuleFlagEntry &MFE : ModuleFlags) {
314 if (Key == MFE.Key->getString())
315 return MFE.Val;
317 return nullptr;
320 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
321 /// represents module-level flags. This method returns null if there are no
322 /// module-level flags.
323 NamedMDNode *Module::getModuleFlagsMetadata() const {
324 return getNamedMetadata("llvm.module.flags");
327 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
328 /// represents module-level flags. If module-level flags aren't found, it
329 /// creates the named metadata that contains them.
330 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
331 return getOrInsertNamedMetadata("llvm.module.flags");
334 /// addModuleFlag - Add a module-level flag to the module-level flags
335 /// metadata. It will create the module-level flags named metadata if it doesn't
336 /// already exist.
337 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
338 Metadata *Val) {
339 Type *Int32Ty = Type::getInt32Ty(Context);
340 Metadata *Ops[3] = {
341 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
342 MDString::get(Context, Key), Val};
343 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
345 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
346 Constant *Val) {
347 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
349 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
350 uint32_t Val) {
351 Type *Int32Ty = Type::getInt32Ty(Context);
352 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
354 void Module::addModuleFlag(MDNode *Node) {
355 assert(Node->getNumOperands() == 3 &&
356 "Invalid number of operands for module flag!");
357 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
358 isa<MDString>(Node->getOperand(1)) &&
359 "Invalid operand types for module flag!");
360 getOrInsertModuleFlagsMetadata()->addOperand(Node);
363 void Module::setDataLayout(StringRef Desc) {
364 DL.reset(Desc);
367 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
369 const DataLayout &Module::getDataLayout() const { return DL; }
371 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
372 return cast<DICompileUnit>(CUs->getOperand(Idx));
374 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
375 return cast<DICompileUnit>(CUs->getOperand(Idx));
378 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
379 while (CUs && (Idx < CUs->getNumOperands()) &&
380 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
381 ++Idx;
384 //===----------------------------------------------------------------------===//
385 // Methods to control the materialization of GlobalValues in the Module.
387 void Module::setMaterializer(GVMaterializer *GVM) {
388 assert(!Materializer &&
389 "Module already has a GVMaterializer. Call materializeAll"
390 " to clear it out before setting another one.");
391 Materializer.reset(GVM);
394 Error Module::materialize(GlobalValue *GV) {
395 if (!Materializer)
396 return Error::success();
398 return Materializer->materialize(GV);
401 Error Module::materializeAll() {
402 if (!Materializer)
403 return Error::success();
404 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
405 return M->materializeModule();
408 Error Module::materializeMetadata() {
409 if (!Materializer)
410 return Error::success();
411 return Materializer->materializeMetadata();
414 //===----------------------------------------------------------------------===//
415 // Other module related stuff.
418 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
419 // If we have a materializer, it is possible that some unread function
420 // uses a type that is currently not visible to a TypeFinder, so ask
421 // the materializer which types it created.
422 if (Materializer)
423 return Materializer->getIdentifiedStructTypes();
425 std::vector<StructType *> Ret;
426 TypeFinder SrcStructTypes;
427 SrcStructTypes.run(*this, true);
428 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
429 return Ret;
432 // dropAllReferences() - This function causes all the subelements to "let go"
433 // of all references that they are maintaining. This allows one to 'delete' a
434 // whole module at a time, even though there may be circular references... first
435 // all references are dropped, and all use counts go to zero. Then everything
436 // is deleted for real. Note that no operations are valid on an object that
437 // has "dropped all references", except operator delete.
439 void Module::dropAllReferences() {
440 for (Function &F : *this)
441 F.dropAllReferences();
443 for (GlobalVariable &GV : globals())
444 GV.dropAllReferences();
446 for (GlobalAlias &GA : aliases())
447 GA.dropAllReferences();
449 for (GlobalIFunc &GIF : ifuncs())
450 GIF.dropAllReferences();
453 unsigned Module::getNumberRegisterParameters() const {
454 auto *Val =
455 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
456 if (!Val)
457 return 0;
458 return cast<ConstantInt>(Val->getValue())->getZExtValue();
461 unsigned Module::getDwarfVersion() const {
462 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
463 if (!Val)
464 return 0;
465 return cast<ConstantInt>(Val->getValue())->getZExtValue();
468 unsigned Module::getCodeViewFlag() const {
469 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
470 if (!Val)
471 return 0;
472 return cast<ConstantInt>(Val->getValue())->getZExtValue();
475 unsigned Module::getInstructionCount() {
476 unsigned NumInstrs = 0;
477 for (Function &F : FunctionList)
478 NumInstrs += F.getInstructionCount();
479 return NumInstrs;
482 Comdat *Module::getOrInsertComdat(StringRef Name) {
483 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
484 Entry.second.Name = &Entry;
485 return &Entry.second;
488 PICLevel::Level Module::getPICLevel() const {
489 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
491 if (!Val)
492 return PICLevel::NotPIC;
494 return static_cast<PICLevel::Level>(
495 cast<ConstantInt>(Val->getValue())->getZExtValue());
498 void Module::setPICLevel(PICLevel::Level PL) {
499 addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
502 PIELevel::Level Module::getPIELevel() const {
503 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
505 if (!Val)
506 return PIELevel::Default;
508 return static_cast<PIELevel::Level>(
509 cast<ConstantInt>(Val->getValue())->getZExtValue());
512 void Module::setPIELevel(PIELevel::Level PL) {
513 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
516 Optional<CodeModel::Model> Module::getCodeModel() const {
517 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
519 if (!Val)
520 return None;
522 return static_cast<CodeModel::Model>(
523 cast<ConstantInt>(Val->getValue())->getZExtValue());
526 void Module::setCodeModel(CodeModel::Model CL) {
527 // Linking object files with different code models is undefined behavior
528 // because the compiler would have to generate additional code (to span
529 // longer jumps) if a larger code model is used with a smaller one.
530 // Therefore we will treat attempts to mix code models as an error.
531 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
534 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
535 if (Kind == ProfileSummary::PSK_CSInstr)
536 addModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
537 else
538 addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
541 Metadata *Module::getProfileSummary(bool IsCS) {
542 return (IsCS ? getModuleFlag("CSProfileSummary")
543 : getModuleFlag("ProfileSummary"));
546 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
547 OwnedMemoryBuffer = std::move(MB);
550 bool Module::getRtLibUseGOT() const {
551 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
552 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
555 void Module::setRtLibUseGOT() {
556 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
559 void Module::setSDKVersion(const VersionTuple &V) {
560 SmallVector<unsigned, 3> Entries;
561 Entries.push_back(V.getMajor());
562 if (auto Minor = V.getMinor()) {
563 Entries.push_back(*Minor);
564 if (auto Subminor = V.getSubminor())
565 Entries.push_back(*Subminor);
566 // Ignore the 'build' component as it can't be represented in the object
567 // file.
569 addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
570 ConstantDataArray::get(Context, Entries));
573 VersionTuple Module::getSDKVersion() const {
574 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
575 if (!CM)
576 return {};
577 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
578 if (!Arr)
579 return {};
580 auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
581 if (Index >= Arr->getNumElements())
582 return None;
583 return (unsigned)Arr->getElementAsInteger(Index);
585 auto Major = getVersionComponent(0);
586 if (!Major)
587 return {};
588 VersionTuple Result = VersionTuple(*Major);
589 if (auto Minor = getVersionComponent(1)) {
590 Result = VersionTuple(*Major, *Minor);
591 if (auto Subminor = getVersionComponent(2)) {
592 Result = VersionTuple(*Major, *Minor, *Subminor);
595 return Result;
598 GlobalVariable *llvm::collectUsedGlobalVariables(
599 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
600 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
601 GlobalVariable *GV = M.getGlobalVariable(Name);
602 if (!GV || !GV->hasInitializer())
603 return GV;
605 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
606 for (Value *Op : Init->operands()) {
607 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
608 Set.insert(G);
610 return GV;