Initial checkin of name mangling code moved from linker
[oota-llvm.git] / support / lib / Support / NameMangling.cpp
1 //===- NameMangling.cpp - Name Mangling for LLVM ----------------------------=//
2 //
3 // This file implements a consistent scheme for name mangling symbols.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Support/NameMangling.h"
8 #include "llvm/DerivedTypes.h"
9 #include "llvm/GlobalValue.h"
10
11 // MangleTypeName - Implement a consistent name-mangling scheme for
12 //                  a given type.
13 // 
14 string MangleTypeName(const Type *Ty) {
15   string mangledName;
16   if (Ty->isPrimitiveType()) {
17     const string &longName = Ty->getDescription();
18     return string(longName.c_str(), (longName.length() < 2) ? 1 : 2);
19   } else if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
20     mangledName = string("P_" + MangleTypeName(PTy->getValueType()));
21   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
22     mangledName = string("S_");
23     for (unsigned i=0; i < STy->getNumContainedTypes(); ++i)
24       mangledName += MangleTypeName(STy->getContainedType(i));
25   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
26     mangledName = string("A_" +MangleTypeName(ATy->getElementType()));
27   } else if (MethodType *MTy = dyn_cast<MethodType>(Ty)) {
28     mangledName = string("M_") + MangleTypeName(MTy->getReturnType());
29     for (unsigned i = 1; i < MTy->getNumContainedTypes(); ++i)
30       mangledName += string(MangleTypeName(MTy->getContainedType(i)));
31   }
32   
33   return mangledName;
34 }
35
36 // mangleName - implement a consistent name-mangling scheme for all
37 // externally visible (i.e., global) objects.
38 // privateName should be unique within the module.
39 // 
40 string MangleName(const string &privateName, const Value *V) {
41   // Lets drop the P_ before every global name since all globals are ptrs
42   return privateName + "_" +
43     MangleTypeName(isa<GlobalValue>(V)
44                    ? cast<GlobalValue>(V)->getType()->getValueType()
45                    : V->getType());
46 }