1 //===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
3 // Unified name mangler for CWriter and assembly backends.
5 //===----------------------------------------------------------------------===//
10 #include "llvm/Value.h"
11 #include "llvm/Module.h"
12 #include "llvm/Type.h"
13 #include "Support/StringExtras.h"
14 #include "llvm/Support/Mangler.h"
16 /// makeNameProper - We don't want identifier names with ., space, or
17 /// - in them, so we mangle these characters into the strings "d_",
18 /// "s_", and "D_", respectively.
20 std::string Mangler::makeNameProper(const std::string &x) {
22 for (std::string::const_iterator sI = x.begin(), sEnd = x.end();
25 case '.': tmp += "d_"; break;
26 case ' ': tmp += "s_"; break;
27 case '-': tmp += "D_"; break;
33 std::string Mangler::getValueName(const Value *V) {
34 // Check to see whether we've already named V.
35 ValueMap::iterator VI = Memo.find(V);
36 if (VI != Memo.end()) {
37 return VI->second; // Return the old name for V.
41 if (V->hasName()) { // Print out the label if it exists...
42 // Name mangling occurs as follows:
43 // - If V is not a global, mangling always occurs.
44 // - Otherwise, mangling occurs when any of the following are true:
45 // 1) V has internal linkage
46 // 2) V's name would collide if it is not mangled.
48 const GlobalValue* gv = dyn_cast<GlobalValue>(V);
49 if(gv && !gv->hasInternalLinkage() && !MangledGlobals.count(gv)) {
50 name = makeNameProper(gv->getName());
52 // Non-global, or global with internal linkage / colliding name
54 name = "l" + utostr(V->getType()->getUniqueID()) + "_" +
55 makeNameProper(V->getName());
58 name = "ltmp_" + utostr(Count++) + "_"
59 + utostr(V->getType()->getUniqueID());
65 Mangler::Mangler(Module &M_) : M(M_)
67 // Calculate which global values have names that will collide when we throw
68 // away type information.
69 std::set<std::string> FoundNames;
70 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
71 if (I->hasName()) // If the global has a name...
72 if (FoundNames.count(I->getName())) // And the name is already used
73 MangledGlobals.insert(I); // Mangle the name
75 FoundNames.insert(I->getName()); // Otherwise, keep track of name
77 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
78 if (I->hasName()) // If the global has a name...
79 if (FoundNames.count(I->getName())) // And the name is already used
80 MangledGlobals.insert(I); // Mangle the name
82 FoundNames.insert(I->getName()); // Otherwise, keep track of name