1 //===-- Function.cpp - Implement the Global object classes ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Function class for the IR library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Function.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/CodeGen/ValueTypes.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Support/InstIterator.h"
26 #include "llvm/Support/LeakDetector.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/RWMutex.h"
29 #include "llvm/Support/StringPool.h"
30 #include "llvm/Support/Threading.h"
33 // Explicit instantiations of SymbolTableListTraits since some of the methods
34 // are not in the public header file...
35 template class llvm::SymbolTableListTraits<Argument, Function>;
36 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
38 //===----------------------------------------------------------------------===//
39 // Argument Implementation
40 //===----------------------------------------------------------------------===//
42 void Argument::anchor() { }
44 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
45 : Value(Ty, Value::ArgumentVal) {
48 // Make sure that we get added to a function
49 LeakDetector::addGarbageObject(this);
52 Par->getArgumentList().push_back(this);
56 void Argument::setParent(Function *parent) {
58 LeakDetector::addGarbageObject(this);
61 LeakDetector::removeGarbageObject(this);
64 /// getArgNo - Return the index of this formal argument in its containing
65 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
66 unsigned Argument::getArgNo() const {
67 const Function *F = getParent();
68 assert(F && "Argument is not in a function");
70 Function::const_arg_iterator AI = F->arg_begin();
72 for (; &*AI != this; ++AI)
78 /// hasByValAttr - Return true if this argument has the byval attribute on it
79 /// in its containing function.
80 bool Argument::hasByValAttr() const {
81 if (!getType()->isPointerTy()) return false;
82 return getParent()->getAttributes().
83 hasAttribute(getArgNo()+1, Attribute::ByVal);
86 unsigned Argument::getParamAlignment() const {
87 assert(getType()->isPointerTy() && "Only pointers have alignments");
88 return getParent()->getParamAlignment(getArgNo()+1);
92 /// hasNestAttr - Return true if this argument has the nest attribute on
93 /// it in its containing function.
94 bool Argument::hasNestAttr() const {
95 if (!getType()->isPointerTy()) return false;
96 return getParent()->getAttributes().
97 hasAttribute(getArgNo()+1, Attribute::Nest);
100 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
101 /// it in its containing function.
102 bool Argument::hasNoAliasAttr() const {
103 if (!getType()->isPointerTy()) return false;
104 return getParent()->getAttributes().
105 hasAttribute(getArgNo()+1, Attribute::NoAlias);
108 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
109 /// on it in its containing function.
110 bool Argument::hasNoCaptureAttr() const {
111 if (!getType()->isPointerTy()) return false;
112 return getParent()->getAttributes().
113 hasAttribute(getArgNo()+1, Attribute::NoCapture);
116 /// hasSRetAttr - Return true if this argument has the sret attribute on
117 /// it in its containing function.
118 bool Argument::hasStructRetAttr() const {
119 if (!getType()->isPointerTy()) return false;
120 if (this != getParent()->arg_begin())
121 return false; // StructRet param must be first param
122 return getParent()->getAttributes().
123 hasAttribute(1, Attribute::StructRet);
126 /// addAttr - Add attributes to an argument.
127 void Argument::addAttr(AttributeSet AS) {
128 getParent()->addAttributes(getArgNo() + 1, AS);
131 /// removeAttr - Remove attributes from an argument.
132 void Argument::removeAttr(AttributeSet AS) {
133 getParent()->removeAttributes(getArgNo() + 1, AS);
136 //===----------------------------------------------------------------------===//
137 // Helper Methods in Function
138 //===----------------------------------------------------------------------===//
140 LLVMContext &Function::getContext() const {
141 return getType()->getContext();
144 FunctionType *Function::getFunctionType() const {
145 return cast<FunctionType>(getType()->getElementType());
148 bool Function::isVarArg() const {
149 return getFunctionType()->isVarArg();
152 Type *Function::getReturnType() const {
153 return getFunctionType()->getReturnType();
156 void Function::removeFromParent() {
157 getParent()->getFunctionList().remove(this);
160 void Function::eraseFromParent() {
161 getParent()->getFunctionList().erase(this);
164 //===----------------------------------------------------------------------===//
165 // Function Implementation
166 //===----------------------------------------------------------------------===//
168 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
169 const Twine &name, Module *ParentModule)
170 : GlobalValue(PointerType::getUnqual(Ty),
171 Value::FunctionVal, 0, 0, Linkage, name) {
172 assert(FunctionType::isValidReturnType(getReturnType()) &&
173 "invalid return type");
174 SymTab = new ValueSymbolTable();
176 // If the function has arguments, mark them as lazily built.
177 if (Ty->getNumParams())
178 setValueSubclassData(1); // Set the "has lazy arguments" bit.
180 // Make sure that we get added to a function
181 LeakDetector::addGarbageObject(this);
184 ParentModule->getFunctionList().push_back(this);
186 // Ensure intrinsics have the right parameter attributes.
187 if (unsigned IID = getIntrinsicID())
188 setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
192 Function::~Function() {
193 dropAllReferences(); // After this it is safe to delete instructions.
195 // Delete all of the method arguments and unlink from symbol table...
196 ArgumentList.clear();
199 // Remove the function from the on-the-side GC table.
203 void Function::BuildLazyArguments() const {
204 // Create the arguments vector, all arguments start out unnamed.
205 FunctionType *FT = getFunctionType();
206 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
207 assert(!FT->getParamType(i)->isVoidTy() &&
208 "Cannot have void typed arguments!");
209 ArgumentList.push_back(new Argument(FT->getParamType(i)));
212 // Clear the lazy arguments bit.
213 unsigned SDC = getSubclassDataFromValue();
214 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
217 size_t Function::arg_size() const {
218 return getFunctionType()->getNumParams();
220 bool Function::arg_empty() const {
221 return getFunctionType()->getNumParams() == 0;
224 void Function::setParent(Module *parent) {
226 LeakDetector::addGarbageObject(this);
229 LeakDetector::removeGarbageObject(this);
232 // dropAllReferences() - This function causes all the subinstructions to "let
233 // go" of all references that they are maintaining. This allows one to
234 // 'delete' a whole class at a time, even though there may be circular
235 // references... first all references are dropped, and all use counts go to
236 // zero. Then everything is deleted for real. Note that no operations are
237 // valid on an object that has "dropped all references", except operator
240 void Function::dropAllReferences() {
241 for (iterator I = begin(), E = end(); I != E; ++I)
242 I->dropAllReferences();
244 // Delete all basic blocks. They are now unused, except possibly by
245 // blockaddresses, but BasicBlock's destructor takes care of those.
246 while (!BasicBlocks.empty())
247 BasicBlocks.begin()->eraseFromParent();
250 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
251 AttributeSet PAL = getAttributes();
252 PAL = PAL.addAttribute(getContext(), i, attr);
256 void Function::addAttributes(unsigned i, AttributeSet attrs) {
257 AttributeSet PAL = getAttributes();
258 PAL = PAL.addAttributes(getContext(), i, attrs);
262 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
263 AttributeSet PAL = getAttributes();
264 PAL = PAL.removeAttributes(getContext(), i, attrs);
268 // Maintain the GC name for each function in an on-the-side table. This saves
269 // allocating an additional word in Function for programs which do not use GC
270 // (i.e., most programs) at the cost of increased overhead for clients which do
272 static DenseMap<const Function*,PooledStringPtr> *GCNames;
273 static StringPool *GCNamePool;
274 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
276 bool Function::hasGC() const {
277 sys::SmartScopedReader<true> Reader(*GCLock);
278 return GCNames && GCNames->count(this);
281 const char *Function::getGC() const {
282 assert(hasGC() && "Function has no collector");
283 sys::SmartScopedReader<true> Reader(*GCLock);
284 return *(*GCNames)[this];
287 void Function::setGC(const char *Str) {
288 sys::SmartScopedWriter<true> Writer(*GCLock);
290 GCNamePool = new StringPool();
292 GCNames = new DenseMap<const Function*,PooledStringPtr>();
293 (*GCNames)[this] = GCNamePool->intern(Str);
296 void Function::clearGC() {
297 sys::SmartScopedWriter<true> Writer(*GCLock);
299 GCNames->erase(this);
300 if (GCNames->empty()) {
303 if (GCNamePool->empty()) {
311 /// copyAttributesFrom - copy all additional attributes (those not needed to
312 /// create a Function) from the Function Src to this one.
313 void Function::copyAttributesFrom(const GlobalValue *Src) {
314 assert(isa<Function>(Src) && "Expected a Function!");
315 GlobalValue::copyAttributesFrom(Src);
316 const Function *SrcF = cast<Function>(Src);
317 setCallingConv(SrcF->getCallingConv());
318 setAttributes(SrcF->getAttributes());
320 setGC(SrcF->getGC());
325 /// getIntrinsicID - This method returns the ID number of the specified
326 /// function, or Intrinsic::not_intrinsic if the function is not an
327 /// intrinsic, or if the pointer is null. This value is always defined to be
328 /// zero to allow easy checking for whether a function is intrinsic or not. The
329 /// particular intrinsic functions which correspond to this value are defined in
330 /// llvm/Intrinsics.h.
332 unsigned Function::getIntrinsicID() const {
333 const ValueName *ValName = this->getValueName();
334 if (!ValName || !isIntrinsic())
336 unsigned Len = ValName->getKeyLength();
337 const char *Name = ValName->getKeyData();
339 #define GET_FUNCTION_RECOGNIZER
340 #include "llvm/IR/Intrinsics.gen"
341 #undef GET_FUNCTION_RECOGNIZER
345 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
346 assert(id < num_intrinsics && "Invalid intrinsic ID!");
347 static const char * const Table[] = {
349 #define GET_INTRINSIC_NAME_TABLE
350 #include "llvm/IR/Intrinsics.gen"
351 #undef GET_INTRINSIC_NAME_TABLE
355 std::string Result(Table[id]);
356 for (unsigned i = 0; i < Tys.size(); ++i) {
357 if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
358 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
359 EVT::getEVT(PTyp->getElementType()).getEVTString();
362 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
368 /// IIT_Info - These are enumerators that describe the entries returned by the
369 /// getIntrinsicInfoTableEntries function.
371 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
373 // Common values should be encoded with 0-15.
391 // Values from 16+ are only encodable with the inefficient encoding.
394 IIT_EMPTYSTRUCT = 18,
399 IIT_EXTEND_VEC_ARG = 23,
400 IIT_TRUNC_VEC_ARG = 24,
405 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
406 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
407 IIT_Info Info = IIT_Info(Infos[NextElt++]);
408 unsigned StructElts = 2;
409 using namespace Intrinsic;
413 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
416 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
419 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
422 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
425 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
428 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
431 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
434 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
437 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
440 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
443 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
446 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
447 DecodeIITType(NextElt, Infos, OutputTable);
450 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
451 DecodeIITType(NextElt, Infos, OutputTable);
454 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
455 DecodeIITType(NextElt, Infos, OutputTable);
458 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
459 DecodeIITType(NextElt, Infos, OutputTable);
462 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
463 DecodeIITType(NextElt, Infos, OutputTable);
466 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
467 DecodeIITType(NextElt, Infos, OutputTable);
469 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
470 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
472 DecodeIITType(NextElt, Infos, OutputTable);
476 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
477 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
480 case IIT_EXTEND_VEC_ARG: {
481 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
482 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendVecArgument,
486 case IIT_TRUNC_VEC_ARG: {
487 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
488 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncVecArgument,
492 case IIT_EMPTYSTRUCT:
493 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
495 case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
496 case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
497 case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
499 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
501 for (unsigned i = 0; i != StructElts; ++i)
502 DecodeIITType(NextElt, Infos, OutputTable);
506 llvm_unreachable("unhandled");
510 #define GET_INTRINSIC_GENERATOR_GLOBAL
511 #include "llvm/IR/Intrinsics.gen"
512 #undef GET_INTRINSIC_GENERATOR_GLOBAL
514 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
515 SmallVectorImpl<IITDescriptor> &T){
516 // Check to see if the intrinsic's type was expressible by the table.
517 unsigned TableVal = IIT_Table[id-1];
519 // Decode the TableVal into an array of IITValues.
520 SmallVector<unsigned char, 8> IITValues;
521 ArrayRef<unsigned char> IITEntries;
522 unsigned NextElt = 0;
523 if ((TableVal >> 31) != 0) {
524 // This is an offset into the IIT_LongEncodingTable.
525 IITEntries = IIT_LongEncodingTable;
527 // Strip sentinel bit.
528 NextElt = (TableVal << 1) >> 1;
530 // Decode the TableVal into an array of IITValues. If the entry was encoded
531 // into a single word in the table itself, decode it now.
533 IITValues.push_back(TableVal & 0xF);
537 IITEntries = IITValues;
541 // Okay, decode the table into the output vector of IITDescriptors.
542 DecodeIITType(NextElt, IITEntries, T);
543 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
544 DecodeIITType(NextElt, IITEntries, T);
548 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
549 ArrayRef<Type*> Tys, LLVMContext &Context) {
550 using namespace Intrinsic;
551 IITDescriptor D = Infos.front();
552 Infos = Infos.slice(1);
555 case IITDescriptor::Void: return Type::getVoidTy(Context);
556 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
557 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
558 case IITDescriptor::Half: return Type::getHalfTy(Context);
559 case IITDescriptor::Float: return Type::getFloatTy(Context);
560 case IITDescriptor::Double: return Type::getDoubleTy(Context);
562 case IITDescriptor::Integer:
563 return IntegerType::get(Context, D.Integer_Width);
564 case IITDescriptor::Vector:
565 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
566 case IITDescriptor::Pointer:
567 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
568 D.Pointer_AddressSpace);
569 case IITDescriptor::Struct: {
571 assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
572 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
573 Elts[i] = DecodeFixedType(Infos, Tys, Context);
574 return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
577 case IITDescriptor::Argument:
578 return Tys[D.getArgumentNumber()];
579 case IITDescriptor::ExtendVecArgument:
580 return VectorType::getExtendedElementVectorType(cast<VectorType>(
581 Tys[D.getArgumentNumber()]));
583 case IITDescriptor::TruncVecArgument:
584 return VectorType::getTruncatedElementVectorType(cast<VectorType>(
585 Tys[D.getArgumentNumber()]));
587 llvm_unreachable("unhandled");
592 FunctionType *Intrinsic::getType(LLVMContext &Context,
593 ID id, ArrayRef<Type*> Tys) {
594 SmallVector<IITDescriptor, 8> Table;
595 getIntrinsicInfoTableEntries(id, Table);
597 ArrayRef<IITDescriptor> TableRef = Table;
598 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
600 SmallVector<Type*, 8> ArgTys;
601 while (!TableRef.empty())
602 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
604 return FunctionType::get(ResultTy, ArgTys, false);
607 bool Intrinsic::isOverloaded(ID id) {
608 #define GET_INTRINSIC_OVERLOAD_TABLE
609 #include "llvm/IR/Intrinsics.gen"
610 #undef GET_INTRINSIC_OVERLOAD_TABLE
613 /// This defines the "Intrinsic::getAttributes(ID id)" method.
614 #define GET_INTRINSIC_ATTRIBUTES
615 #include "llvm/IR/Intrinsics.gen"
616 #undef GET_INTRINSIC_ATTRIBUTES
618 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
619 // There can never be multiple globals with the same name of different types,
620 // because intrinsics must be a specific type.
622 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
623 getType(M->getContext(), id, Tys)));
626 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
627 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
628 #include "llvm/IR/Intrinsics.gen"
629 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
631 /// hasAddressTaken - returns true if there are any uses of this function
632 /// other than direct calls or invokes to it.
633 bool Function::hasAddressTaken(const User* *PutOffender) const {
634 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
636 if (isa<BlockAddress>(U))
638 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
639 return PutOffender ? (*PutOffender = U, true) : true;
640 ImmutableCallSite CS(cast<Instruction>(U));
642 return PutOffender ? (*PutOffender = U, true) : true;
647 bool Function::isDefTriviallyDead() const {
649 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
650 !hasAvailableExternallyLinkage())
653 // Check if the function is used by anything other than a blockaddress.
654 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
655 if (!isa<BlockAddress>(*I))
661 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
662 /// setjmp or other function that gcc recognizes as "returning twice".
663 bool Function::callsFunctionThatReturnsTwice() const {
664 for (const_inst_iterator
665 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
666 const CallInst* callInst = dyn_cast<CallInst>(&*I);
669 if (callInst->canReturnTwice())