本文整理汇总了C++中GlobalVariable::getInitializer方法的典型用法代码示例。如果您正苦于以下问题:C++ GlobalVariable::getInitializer方法的具体用法?C++ GlobalVariable::getInitializer怎么用?C++ GlobalVariable::getInitializer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类GlobalVariable
的用法示例。
在下文中一共展示了GlobalVariable::getInitializer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: moveGlobalVariableInitializer
void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
ValueToValueMapTy &VMap,
ValueMaterializer *Materializer,
GlobalVariable *NewGV) {
assert(OrigGV.hasInitializer() && "Nothing to move");
if (!NewGV)
NewGV = cast<GlobalVariable>(VMap[&OrigGV]);
else
assert(VMap[&OrigGV] == NewGV &&
"Incorrect global variable mapping in VMap.");
assert(NewGV->getParent() != OrigGV.getParent() &&
"moveGlobalVariable should only be used to move initializers between "
"modules");
NewGV->setInitializer(MapValue(OrigGV.getInitializer(), VMap, RF_None,
nullptr, Materializer));
}
示例2: isSimpleEnoughPointerToCommit
/// Return true if this constant is simple enough for us to understand. In
/// particular, if it is a cast to anything other than from one pointer type to
/// another pointer type, we punt. We basically just support direct accesses to
/// globals and GEP's of globals. This should be kept up to date with
/// CommitValueTo.
static bool isSimpleEnoughPointerToCommit(Constant *C) {
// Conservatively, avoid aggregate types. This is because we don't
// want to worry about them partially overlapping other stores.
if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
return false;
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
// Do not allow weak/*_odr/linkonce linkage or external globals.
return GV->hasUniqueInitializer();
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
// Handle a constantexpr gep.
if (CE->getOpcode() == Instruction::GetElementPtr &&
isa<GlobalVariable>(CE->getOperand(0)) &&
cast<GEPOperator>(CE)->isInBounds()) {
GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
// Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
// external globals.
if (!GV->hasUniqueInitializer())
return false;
// The first index must be zero.
ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
if (!CI || !CI->isZero()) return false;
// The remaining indices must be compile-time known integers within the
// notional bounds of the corresponding static array types.
if (!CE->isGEPWithNoNotionalOverIndexing())
return false;
return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
// A constantexpr bitcast from a pointer to another pointer is a no-op,
// and we know how to evaluate it by moving the bitcast from the pointer
// operand to the value operand.
} else if (CE->getOpcode() == Instruction::BitCast &&
isa<GlobalVariable>(CE->getOperand(0))) {
// Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
// external globals.
return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
}
}
return false;
}
示例3: readAnnotate
std::string readAnnotate(Function *f) {
std::string annotation = "";
// Get annotation variable
GlobalVariable *glob =
f->getParent()->getGlobalVariable("llvm.global.annotations");
if (glob != NULL) {
// Get the array
if (ConstantArray *ca = dyn_cast<ConstantArray>(glob->getInitializer())) {
for (unsigned i = 0; i < ca->getNumOperands(); ++i) {
// Get the struct
if (ConstantStruct *structAn =
dyn_cast<ConstantStruct>(ca->getOperand(i))) {
if (ConstantExpr *expr =
dyn_cast<ConstantExpr>(structAn->getOperand(0))) {
// If it's a bitcast we can check if the annotation is concerning
// the current function
if (expr->getOpcode() == Instruction::BitCast &&
expr->getOperand(0) == f) {
ConstantExpr *note = cast<ConstantExpr>(structAn->getOperand(1));
// If it's a GetElementPtr, that means we found the variable
// containing the annotations
if (note->getOpcode() == Instruction::GetElementPtr) {
if (GlobalVariable *annoteStr =
dyn_cast<GlobalVariable>(note->getOperand(0))) {
if (ConstantDataSequential *data =
dyn_cast<ConstantDataSequential>(
annoteStr->getInitializer())) {
if (data->isString()) {
annotation += data->getAsString().lower() + " ";
}
}
}
}
}
}
}
}
}
}
return annotation;
}
示例4: doInitialization
// doInitialization - Initializes the vector of functions that have been
// annotated with the noinline attribute.
bool SimpleInliner::doInitialization(CallGraph &CG) {
CA.setTargetData(getAnalysisIfAvailable<TargetData>());
Module &M = CG.getModule();
for (Module::iterator I = M.begin(), E = M.end();
I != E; ++I)
if (!I->isDeclaration() && I->hasFnAttr(Attribute::NoInline))
NeverInline.insert(I);
// Get llvm.noinline
GlobalVariable *GV = M.getNamedGlobal("llvm.noinline");
if (GV == 0)
return false;
// Don't crash on invalid code
if (!GV->hasDefinitiveInitializer())
return false;
const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
if (InitList == 0)
return false;
// Iterate over each element and add to the NeverInline set
for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
// Get Source
const Constant *Elt = InitList->getOperand(i);
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Elt))
if (CE->getOpcode() == Instruction::BitCast)
Elt = CE->getOperand(0);
// Insert into set of functions to never inline
if (const Function *F = dyn_cast<Function>(Elt))
NeverInline.insert(F);
}
return false;
}
示例5: get_legup_label
std::string ModuloScheduler::get_legup_label(BasicBlock *bb) {
std::string label = "";
for (BasicBlock::iterator instr = bb->begin(), ie = bb->end(); instr != ie;
++instr) {
const CallInst *ci = dyn_cast<CallInst>(instr);
if (!ci)
continue;
Function *calledFunc = ci->getCalledFunction();
// ignore indirect function invocations
if (!calledFunc)
continue;
if (calledFunc->getName() == "__legup_label") {
// errs() << "Found label: " << *ci << "\n";
Value *str = *ci->op_begin();
// handle getelementptr
if (const User *U = dyn_cast<User>(str)) {
if (U->getNumOperands() > 1) {
str = U->getOperand(0);
}
}
GlobalVariable *G = dyn_cast<GlobalVariable>(str);
assert(G);
Constant *C = G->getInitializer();
assert(C);
// TODO: LLVM 3.4 update
// ConstantArray *CA = dyn_cast<ConstantArray>(C);
if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
assert(CA);
label = arrayToString(CA);
} else if (ConstantDataArray *CA = dyn_cast<ConstantDataArray>(C)) {
assert(CA);
label = CA->getAsCString();
}
return label;
}
}
return label;
}
示例6: ParseAssertionLocation
void AssertionSiteInstrumenter::ParseAssertionLocation(
Location *Loc, CallInst *Call) {
assert(Call->getCalledFunction()->getName() == INLINE_ASSERTION);
if (Call->getNumArgOperands() < 4)
panic("TESLA assertion must have at least 4 arguments");
// The filename (argument 1) should be a global variable.
GlobalVariable *NameVar =
dyn_cast<GlobalVariable>(Call->getOperand(1)->stripPointerCasts());
ConstantDataArray *A;
if (!NameVar ||
!(A = dyn_cast_or_null<ConstantDataArray>(NameVar->getInitializer()))) {
Call->dump();
panic("unable to parse filename from TESLA assertion");
}
*Loc->mutable_filename() = A->getAsString();
// The line and counter values should be constant integers.
ConstantInt *Line = dyn_cast<ConstantInt>(Call->getOperand(2));
if (!Line) {
Call->getOperand(2)->dump();
panic("assertion line must be a constant int");
}
Loc->set_line(Line->getLimitedValue(INT_MAX));
ConstantInt *Count = dyn_cast<ConstantInt>(Call->getOperand(3));
if (!Count) {
Call->getOperand(3)->dump();
panic("assertion count must be a constant int");
}
Loc->set_counter(Count->getLimitedValue(INT_MAX));
}
示例7: lowerGlobalCtors
void MemoryInstrumenter::lowerGlobalCtors(Module &M) {
// Find llvm.global_ctors.
GlobalVariable *GV = M.getNamedGlobal("llvm.global_ctors");
if (!GV)
return;
assert(!GV->isDeclaration() && !GV->hasLocalLinkage());
// Should be an array of '{ int, void ()* }' structs. The first value is
// the init priority, which must be 65535 if the bitcode is generated using
// clang.
if (ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer())) {
for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
ConstantStruct *CS =
dyn_cast<ConstantStruct>(InitList->getOperand(i));
assert(CS);
assert(CS->getNumOperands() == 2);
// Get the priority.
ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
assert(Priority);
// TODO: For now, we assume all priorities must be 65535.
assert(Priority->equalsInt(65535));
// Get the constructor function.
Constant *FP = CS->getOperand(1);
if (FP->isNullValue())
break; // Found a null terminator, exit.
// Explicitly call the constructor at the main entry.
CallInst::Create(FP, "", Main->begin()->getFirstNonPHI());
}
}
// Clear the global_ctors array.
// Use eraseFromParent() instead of removeFromParent().
GV->eraseFromParent();
}
示例8: addToGlobalConstructors
void PerfMonitor::addToGlobalConstructors(Function *Fn) {
const char *Name = "llvm.global_ctors";
GlobalVariable *GV = M->getGlobalVariable(Name);
std::vector<Constant *> V;
if (GV) {
Constant *Array = GV->getInitializer();
for (Value *X : Array->operand_values())
V.push_back(cast<Constant>(X));
GV->eraseFromParent();
}
StructType *ST = StructType::get(Builder.getInt32Ty(), Fn->getType(),
Builder.getInt8PtrTy());
V.push_back(
ConstantStruct::get(ST, Builder.getInt32(10), Fn,
ConstantPointerNull::get(Builder.getInt8PtrTy())));
ArrayType *Ty = ArrayType::get(ST, V.size());
GV = new GlobalVariable(*M, Ty, true, GlobalValue::AppendingLinkage,
ConstantArray::get(Ty, V), Name, nullptr,
GlobalVariable::NotThreadLocal);
}
示例9: ConstantFoldLoadThroughGEPConstantExpr
/// Return the value that would be computed by a load from P after the stores
/// reflected by 'memory' have been performed. If we can't decide, return null.
Constant *Evaluator::ComputeLoadResult(Constant *P) {
// If this memory location has been recently stored, use the stored value: it
// is the most up-to-date.
DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
if (I != MutatedMemory.end()) return I->second;
// Access it.
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
if (GV->hasDefinitiveInitializer())
return GV->getInitializer();
return nullptr;
}
// Handle a constantexpr getelementptr.
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
if (CE->getOpcode() == Instruction::GetElementPtr &&
isa<GlobalVariable>(CE->getOperand(0))) {
GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
if (GV->hasDefinitiveInitializer())
return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
}
return nullptr; // don't know how to evaluate.
}
示例10: runOnModule
bool ConstantMerge::runOnModule(Module &M) {
// Find all the globals that are marked "used". These cannot be merged.
SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
// Map unique constant/section pairs to globals. We don't want to merge
// globals in different sections.
DenseMap<Constant*, GlobalVariable*> CMap;
// Replacements - This vector contains a list of replacements to perform.
SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
bool MadeChange = false;
// Iterate constant merging while we are still making progress. Merging two
// constants together may allow us to merge other constants together if the
// second level constants have initializers which point to the globals that
// were just merged.
while (1) {
// First pass: identify all globals that can be merged together, filling in
// the Replacements vector. We cannot do the replacement in this pass
// because doing so may cause initializers of other globals to be rewritten,
// invalidating the Constant* pointers in CMap.
//
for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
GVI != E; ) {
GlobalVariable *GV = GVI++;
// If this GV is dead, remove it.
GV->removeDeadConstantUsers();
if (GV->use_empty() && GV->hasLocalLinkage()) {
GV->eraseFromParent();
continue;
}
// Only process constants with initializers in the default addres space.
if (!GV->isConstant() ||!GV->hasDefinitiveInitializer() ||
GV->getType()->getAddressSpace() != 0 || !GV->getSection().empty() ||
// Don't touch values marked with attribute(used).
UsedGlobals.count(GV))
continue;
Constant *Init = GV->getInitializer();
// Check to see if the initializer is already known.
GlobalVariable *&Slot = CMap[Init];
if (Slot == 0) { // Nope, add it to the map.
Slot = GV;
} else if (GV->hasLocalLinkage()) { // Yup, this is a duplicate!
// Make all uses of the duplicate constant use the canonical version.
Replacements.push_back(std::make_pair(GV, Slot));
}
}
if (Replacements.empty())
return MadeChange;
CMap.clear();
// Now that we have figured out which replacements must be made, do them all
// now. This avoid invalidating the pointers in CMap, which are unneeded
// now.
for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
// Eliminate any uses of the dead global.
Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
// Delete the global value from the module.
Replacements[i].first->eraseFromParent();
}
NumMerged += Replacements.size();
Replacements.clear();
}
}
示例11: findSandboxes
SandboxVector SandboxUtils::findSandboxes(Module& M) {
FunctionIntMap funcToOverhead;
FunctionIntMap funcToClearances;
map<Function*,string> funcToSandboxName;
map<string,FunctionSet> sandboxNameToEntryPoints;
StringSet ephemeralSandboxes;
SandboxVector sandboxes;
// function-level annotations of sandboxed code
Regex *sboxPerfRegex = new Regex("perf_overhead_\\(([0-9]{1,2})\\)", true);
SmallVector<StringRef, 4> matches;
if (GlobalVariable* lga = M.getNamedGlobal("llvm.global.annotations")) {
ConstantArray* lgaArray = dyn_cast<ConstantArray>(lga->getInitializer()->stripPointerCasts());
for (User::op_iterator i=lgaArray->op_begin(), e = lgaArray->op_end(); e!=i; i++) {
ConstantStruct* lgaArrayElement = dyn_cast<ConstantStruct>(i->get());
// get the annotation value first
GlobalVariable* annotationStrVar = dyn_cast<GlobalVariable>(lgaArrayElement->getOperand(1)->stripPointerCasts());
ConstantDataArray* annotationStrArray = dyn_cast<ConstantDataArray>(annotationStrVar->getInitializer());
StringRef annotationStrArrayCString = annotationStrArray->getAsCString();
GlobalValue* annotatedVal = dyn_cast<GlobalValue>(lgaArrayElement->getOperand(0)->stripPointerCasts());
if (isa<Function>(annotatedVal)) {
Function* annotatedFunc = dyn_cast<Function>(annotatedVal);
StringRef sandboxName;
if (annotationStrArrayCString.startswith(SANDBOX_PERSISTENT) || annotationStrArrayCString.startswith(SANDBOX_EPHEMERAL)) {
sandboxEntryPoints.insert(annotatedFunc);
outs() << INDENT_1 << "Found sandbox entrypoint " << annotatedFunc->getName() << "\n";
outs() << INDENT_2 << "Annotation string: " << annotationStrArrayCString << "\n";
if (annotationStrArrayCString.startswith(SANDBOX_PERSISTENT)) {
sandboxName = annotationStrArrayCString.substr(strlen(SANDBOX_PERSISTENT)+1);
}
else if (annotationStrArrayCString.startswith(SANDBOX_EPHEMERAL)) {
sandboxName = annotationStrArrayCString.substr(strlen(SANDBOX_EPHEMERAL)+1);
ephemeralSandboxes.insert(sandboxName);
}
outs() << INDENT_2 << "Sandbox name: " << sandboxName << "\n";
if (funcToSandboxName.find(annotatedFunc) != funcToSandboxName.end()) {
outs() << INDENT_1 << "*** Error: Function " << annotatedFunc->getName() << " is already an entrypoint for another sandbox\n";
}
else {
funcToSandboxName[annotatedFunc] = sandboxName;
sandboxNameToEntryPoints[sandboxName].insert(annotatedFunc);
}
}
else if (sboxPerfRegex->match(annotationStrArrayCString, &matches)) {
int overhead;
outs() << INDENT_2 << "Threshold set to " << matches[1].str() <<
"%\n";
matches[1].getAsInteger(0, overhead);
funcToOverhead[annotatedFunc] = overhead;
}
else if (annotationStrArrayCString.startswith(CLEARANCE)) {
StringRef className = annotationStrArrayCString.substr(strlen(CLEARANCE)+1);
outs() << INDENT_2 << "Sandbox has clearance for \"" << className << "\"\n";
ClassifiedUtils::assignBitIdxToClassName(className);
funcToClearances[annotatedFunc] |= (1 << ClassifiedUtils::getBitIdxFromClassName(className));
}
}
}
}
// TODO: sanity check overhead and clearance annotations
// Combine all annotation information for function-level sandboxes to create Sandbox instances
for (pair<string,FunctionSet> p : sandboxNameToEntryPoints) {
string sandboxName = p.first;
FunctionSet entryPoints = p.second;
int idx = assignBitIdxToSandboxName(sandboxName);
int overhead = 0;
int clearances = 0;
bool persistent = find(ephemeralSandboxes.begin(), ephemeralSandboxes.end(), sandboxName) == ephemeralSandboxes.end();
// set overhead and clearances; any of the entry points could be annotated
for (Function* entryPoint : entryPoints) {
if (funcToOverhead.find(entryPoint) != funcToOverhead.end()) {
overhead = funcToOverhead[entryPoint];
}
if (funcToClearances.find(entryPoint) != funcToClearances.end()) {
clearances = funcToClearances[entryPoint];
}
}
SDEBUG("soaap.util.sandbox", 3, dbgs() << INDENT_2 << "Creating new Sandbox instance for " << sandboxName << "\n");
sandboxes.push_back(new Sandbox(sandboxName, idx, entryPoints, persistent, M, overhead, clearances));
SDEBUG("soaap.util.sandbox", 3, dbgs() << INDENT_2 << "Created new Sandbox instance\n");
}
/*
for (map<Function*,string>::iterator I=funcToSandboxName.begin(), E=funcToSandboxName.end(); I!=E; I++) {
Function* entryPoint = I->first;
string sandboxName = I->second;
int idx = assignBitIdxToSandboxName(sandboxName);
int overhead = funcToOverhead[entryPoint];
int clearances = funcToClearances[entryPoint];
bool persistent = find(ephemeralSandboxes.begin(), ephemeralSandboxes.end(), entryPoint) == ephemeralSandboxes.end();
SDEBUG("soaap.util.sandbox", 3, dbgs() << INDENT_2 << "Creating new Sandbox instance\n");
sandboxes.push_back(new Sandbox(sandboxName, idx, entryPoint, persistent, M, overhead, clearances));
SDEBUG("soaap.util.sandbox", 3, dbgs() << INDENT_2 << "Created new Sandbox instance\n");
}
//.........这里部分代码省略.........
示例12: buildClouds
void SDBuildCHA::buildClouds(Module &M) {
// this set is used for checking if a parent class is defined or not
std::set<vtbl_t> build_undefinedVtables;
for(auto itr = M.getNamedMDList().begin(); itr != M.getNamedMDList().end(); itr++) {
NamedMDNode* md = itr;
// check if this is a metadata that we've added
if(! md->getName().startswith(SD_MD_CLASSINFO))
continue;
//sd_print("GOT METADATA: %s\n", md->getName().data());
std::vector<nmd_t> infoVec = extractMetadata(md);
for (const nmd_t& info : infoVec) {
// record the old vtable array
GlobalVariable* oldVtable = M.getGlobalVariable(info.className, true);
//sd_print("class %s with %d subtables\n", info.className.c_str(), info.subVTables.size());
/*
sd_print("oldvtables: %p, %d, class %s\n",
oldVtable,
oldVtable ? oldVtable->hasInitializer() : -1,
info.className.c_str());
*/
if (oldVtable && oldVtable->hasInitializer()) {
ConstantArray* vtable = dyn_cast<ConstantArray>(oldVtable->getInitializer());
assert(vtable);
oldVTables[info.className] = vtable;
} else {
undefinedVTables.insert(info.className);
}
for(unsigned ind = 0; ind < info.subVTables.size(); ind++) {
const nmd_sub_t* subInfo = & info.subVTables[ind];
vtbl_t name(info.className, ind);
/*
sd_print("SubVtable[%d] Order: %d Parents[%d]: %s [%d-%d] AddrPt: %d\n",
ind,
subInfo->order,
subInfo->parents.size(),
"NYI",
subInfo->start,
subInfo->end,
subInfo->addressPoint);
*/
if (build_undefinedVtables.find(name) != build_undefinedVtables.end()) {
//sd_print("Removing %s,%d from build_udnefinedVtables\n", name.first.c_str(), name.second);
build_undefinedVtables.erase(name);
}
if (cloudMap.find(name) == cloudMap.end()){
//sd_print("Inserting %s, %d in cloudMap\n", name.first.c_str(), name.second);
cloudMap[name] = std::set<vtbl_t>();
}
vtbl_set_t parents;
for (auto it : subInfo->parents) {
if (it.first != "") {
vtbl_t &parent = it;
parents.insert(parent);
// if the parent class is not defined yet, add it to the
// undefined vtable set
if (cloudMap.find(parent) == cloudMap.end()) {
//sd_print("Inserting %s, %d in cloudMap - undefined parent\n", parent.first.c_str(), parent.second);
cloudMap[parent] = std::set<vtbl_t>();
build_undefinedVtables.insert(parent);
}
// add the current class to the parent's children set
cloudMap[parent].insert(name);
} else {
assert(ind == 0); // make sure secondary vtables have a direct parent
// add the class to the root set
roots.insert(info.className);
}
}
parentMap[info.className].push_back(parents);
// record the original address points
addrPtMap[info.className].push_back(subInfo->addressPoint);
// record the sub-vtable ends
rangeMap[info.className].push_back(range_t(subInfo->start, subInfo->end));
}
}
}
if (build_undefinedVtables.size() != 0) {
sd_print("Build Undefined vtables:\n");
for (auto n : build_undefinedVtables) {
sd_print("%s,%d\n", n.first.c_str(), n.second);
}
}
//.........这里部分代码省略.........
示例13: calculateGraphs
//
// Method: postOrderInline()
//
// Description:
// This methods does a post order traversal of the call graph and performs
// bottom-up inlining of the DSGraphs.
//
void
BUDataStructures::postOrderInline (Module & M) {
// Variables used for Tarjan SCC-finding algorithm. These are passed into
// the recursive function used to find SCCs.
std::vector<const Function*> Stack;
std::map<const Function*, unsigned> ValMap;
unsigned NextID = 1;
// Do post order traversal on the global ctors. Use this information to update
// the globals graph.
const char *Name = "llvm.global_ctors";
GlobalVariable *GV = M.getNamedGlobal(Name);
if (GV && !(GV->isDeclaration()) && !(GV->hasLocalLinkage())) {
// Should be an array of '{ int, void ()* }' structs. The first value is
// the init priority, which we ignore.
ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
if (InitList) {
for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
if (CS->getNumOperands() != 2)
break; // Not array of 2-element structs.
Constant *FP = CS->getOperand(1);
if (FP->isNullValue())
break; // Found a null terminator, exit.
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
if (CE->isCast())
FP = CE->getOperand(0);
Function *F = dyn_cast<Function>(FP);
if (F && !F->isDeclaration() && !ValMap.count(F)) {
calculateGraphs(F, Stack, NextID, ValMap);
CloneAuxIntoGlobal(getDSGraph(*F));
}
}
GlobalsGraph->removeTriviallyDeadNodes();
GlobalsGraph->maskIncompleteMarkers();
// Mark external globals incomplete.
GlobalsGraph->markIncompleteNodes(DSGraph::IgnoreGlobals);
GlobalsGraph->computeExternalFlags(DSGraph::DontMarkFormalsExternal);
GlobalsGraph->computeIntPtrFlags();
//
// Create equivalence classes for aliasing globals so that we only need to
// record one global per DSNode.
//
formGlobalECs();
// propogte information calculated
// from the globals graph to the other graphs.
for (Module::iterator F = M.begin(); F != M.end(); ++F) {
if (!(F->isDeclaration())){
DSGraph *Graph = getDSGraph(*F);
cloneGlobalsInto(Graph, DSGraph::DontCloneCallNodes |
DSGraph::DontCloneAuxCallNodes);
Graph->buildCallGraph(callgraph, GlobalFunctionList, filterCallees);
Graph->maskIncompleteMarkers();
Graph->markIncompleteNodes(DSGraph::MarkFormalArgs |
DSGraph::IgnoreGlobals);
Graph->computeExternalFlags(DSGraph::DontMarkFormalsExternal);
Graph->computeIntPtrFlags();
}
}
}
}
//
// Start the post order traversal with the main() function. If there is no
// main() function, don't worry; we'll have a separate traversal for inlining
// graphs for functions not reachable from main().
//
Function *MainFunc = M.getFunction ("main");
if (MainFunc && !MainFunc->isDeclaration()) {
calculateGraphs(MainFunc, Stack, NextID, ValMap);
CloneAuxIntoGlobal(getDSGraph(*MainFunc));
}
//
// Calculate the graphs for any functions that are unreachable from main...
//
for (Function &F : M)
if (!F.isDeclaration() && !ValMap.count(&F)) {
if (MainFunc)
DEBUG(errs() << debugname << ": Function unreachable from main: "
<< F.getName() << "\n");
calculateGraphs(&F, Stack, NextID, ValMap); // Calculate all graphs.
CloneAuxIntoGlobal(getDSGraph(F));
// Mark this graph as processed. Do this by finding all functions
// in the graph that map to it, and mark them visited.
// Note that this really should be handled neatly by calculateGraphs
// itself, not here. However this catches the worst offenders.
DSGraph *G = getDSGraph(F);
//.........这里部分代码省略.........
示例14: runOnModule
bool GenericToNVVM::runOnModule(Module &M) {
// Create a clone of each global variable that has the default address space.
// The clone is created with the global address space specifier, and the pair
// of original global variable and its clone is placed in the GVMap for later
// use.
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E;) {
GlobalVariable *GV = &*I++;
if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
!llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
!llvm::isSampler(*GV) && !GV->getName().startswith("llvm.")) {
GlobalVariable *NewGV = new GlobalVariable(
M, GV->getValueType(), GV->isConstant(),
GV->getLinkage(),
GV->hasInitializer() ? GV->getInitializer() : nullptr,
"", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
NewGV->copyAttributesFrom(GV);
GVMap[GV] = NewGV;
}
}
// Return immediately, if every global variable has a specific address space
// specifier.
if (GVMap.empty()) {
return false;
}
// Walk through the instructions in function defitinions, and replace any use
// of original global variables in GVMap with a use of the corresponding
// copies in GVMap. If necessary, promote constants to instructions.
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (I->isDeclaration()) {
continue;
}
IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
++BBI) {
for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
++II) {
for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
Value *Operand = II->getOperand(i);
if (isa<Constant>(Operand)) {
II->setOperand(
i, remapConstant(&M, &*I, cast<Constant>(Operand), Builder));
}
}
}
}
ConstantToValueMap.clear();
}
// Copy GVMap over to a standard value map.
ValueToValueMapTy VM;
for (auto I = GVMap.begin(), E = GVMap.end(); I != E; ++I)
VM[I->first] = I->second;
// Walk through the metadata section and update the debug information
// associated with the global variables in the default address space.
for (NamedMDNode &I : M.named_metadata()) {
remapNamedMDNode(VM, &I);
}
// Walk through the global variable initializers, and replace any use of
// original global variables in GVMap with a use of the corresponding copies
// in GVMap. The copies need to be bitcast to the original global variable
// types, as we cannot use cvta in global variable initializers.
for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
GlobalVariable *GV = I->first;
GlobalVariable *NewGV = I->second;
// Remove GV from the map so that it can be RAUWed. Note that
// DenseMap::erase() won't invalidate any iterators but this one.
auto Next = std::next(I);
GVMap.erase(I);
I = Next;
Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
// At this point, the remaining uses of GV should be found only in global
// variable initializers, as other uses have been already been removed
// while walking through the instructions in function definitions.
GV->replaceAllUsesWith(BitCastNewGV);
std::string Name = GV->getName();
GV->eraseFromParent();
NewGV->setName(Name);
}
assert(GVMap.empty() && "Expected it to be empty by now");
return true;
}
示例15: wrapValue
DyckVertex* AAAnalyzer::wrapValue(Value * v) {
// if the vertex of v exists, return it, otherwise create one
pair < DyckVertex*, bool> retpair = dgraph->retrieveDyckVertex(v);
if (retpair.second) {
return retpair.first;
}
DyckVertex* vdv = retpair.first;
// constantTy are handled as below.
if (isa<ConstantExpr>(v)) {
// constant expr should be handled like a assignment instruction
if (isa<GEPOperator>(v)) {
DyckVertex * got = handle_gep((GEPOperator*) v);
makeAlias(vdv, got);
} else if (((ConstantExpr*) v)->isCast()) {
// errs() << *v << "\n";
DyckVertex * got = wrapValue(((ConstantExpr*) v)->getOperand(0));
makeAlias(vdv, got);
} else {
unsigned opcode = ((ConstantExpr*) v)->getOpcode();
switch (opcode) {
case 23: // BinaryConstantExpr "and"
case 24: // BinaryConstantExpr "or"
{
// do nothing
}
break;
default:
{
errs() << "ERROR when handle the following constant expression\n";
errs() << *v << "\n";
errs() << ((ConstantExpr*) v)->getOpcode() << "\n";
errs() << ((ConstantExpr*) v)->getOpcodeName() << "\n";
errs().flush();
exit(-1);
}
break;
}
}
} else if (isa<ConstantArray>(v)) {
#ifndef ARRAY_SIMPLIFIED
DyckVertex* ptr = addPtrTo(NULL, vdv, dgraph);
DyckVertex* current = ptr;
Constant * vAgg = (Constant*) v;
int numElmt = vAgg->getNumOperands();
for (int i = 0; i < numElmt; i++) {
Value * vi = vAgg->getOperand(i);
DyckVertex* viptr = addPtrOffset(current, i * dl.getTypeAllocSize(vi->getType()), dgraph);
addPtrTo(viptr, wrapValue(vi, dgraph, dl), dgraph);
}
#else
Constant * vAgg = (Constant*) v;
int numElmt = vAgg->getNumOperands();
for (int i = 0; i < numElmt; i++) {
Value * vi = vAgg->getOperand(i);
makeAlias(vdv, wrapValue(vi));
}
#endif
} else if (isa<ConstantStruct>(v)) {
//DyckVertex* ptr = addPtrTo(NULL, vdv);
//DyckVertex* current = ptr;
Constant * vAgg = (Constant*) v;
int numElmt = vAgg->getNumOperands();
for (int i = 0; i < numElmt; i++) {
Value * vi = vAgg->getOperand(i);
addField(vdv, -2 - i, wrapValue(vi));
}
} else if (isa<GlobalValue>(v)) {
if (isa<GlobalVariable>(v)) {
GlobalVariable * global = (GlobalVariable *) v;
if (global->hasInitializer()) {
Value * initializer = global->getInitializer();
if (!isa<UndefValue>(initializer)) {
DyckVertex * initVer = wrapValue(initializer);
addPtrTo(vdv, initVer);
}
}
} else if (isa<GlobalAlias>(v)) {
GlobalAlias * global = (GlobalAlias *) v;
Value * aliasee = global->getAliasee();
makeAlias(vdv, wrapValue(aliasee));
} else if (isa<Function>(v)) {
// do nothing
} // no else
} else if (isa<ConstantInt>(v) || isa<ConstantFP>(v) || isa<ConstantPointerNull>(v) || isa<UndefValue>(v)) {
// do nothing
} else if (isa<ConstantDataArray>(v) || isa<ConstantAggregateZero>(v)) {
// do nothing
} else if (isa<BlockAddress>(v)) {
// do nothing
} else if (isa<ConstantDataVector>(v)) {
errs() << "ERROR when handle the following ConstantDataSequential, ConstantDataVector\n";
errs() << *v << "\n";
errs().flush();
exit(-1);
} else if (isa<ConstantVector>(v)) {
errs() << "ERROR when handle the following ConstantVector\n";
errs() << *v << "\n";
errs().flush();
//.........这里部分代码省略.........