当前位置: 首页>>代码示例>>C++>>正文


C++ GlobalVariable::setInitializer方法代码示例

本文整理汇总了C++中GlobalVariable::setInitializer方法的典型用法代码示例。如果您正苦于以下问题:C++ GlobalVariable::setInitializer方法的具体用法?C++ GlobalVariable::setInitializer怎么用?C++ GlobalVariable::setInitializer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在GlobalVariable的用法示例。


在下文中一共展示了GlobalVariable::setInitializer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: SetupGlobals

void WorklessInstrument::SetupGlobals(Module * pModule)
{
	assert(pModule->getGlobalVariable("SAMPLE_RATE")==NULL);
	this->SAMPLE_RATE = new GlobalVariable(*pModule, this->IntType, false, GlobalValue::CommonLinkage, 0, "SAMPLE_RATE");
	this->SAMPLE_RATE->setAlignment(4);
	this->SAMPLE_RATE->setInitializer(this->ConstantInt0);

	assert(pModule->getGlobalVariable("PC_SAMPLE_RATE")==NULL);
	this->PC_SAMPLE_RATE = new GlobalVariable(*pModule, this->CharStarType, false, GlobalValue::CommonLinkage, 0, "PC_SAMPLE_RATE");
	this->PC_SAMPLE_RATE->setAlignment(8);
	this->PC_SAMPLE_RATE->setInitializer(this->ConstantNULL);

	assert(pModule->getGlobalVariable("numGlobalCounter")==NULL);
	this->numGlobalCounter = new GlobalVariable( *pModule , this->LongType, false, GlobalValue::ExternalLinkage, 0, "numGlobalCounter");
	this->numGlobalCounter->setAlignment(8);
	this->numGlobalCounter->setInitializer(this->ConstantLong0);

/*
	assert(pModule->getGlobalVariable("numInstances")==NULL);
	this->numInstances = new GlobalVariable(*pModule, this->LongType, false, GlobalVariable::ExternalLinkage, 0, "numInstances");
	this->numInstances->setAlignment(8);
	this->numInstances->setInitializer(this->ConstantLong0);
*/
	assert(pModule->getGlobalVariable("CURRENT_SAMPLE") == NULL);
	this->CURRENT_SAMPLE = new GlobalVariable(*pModule, this->LongType, false, GlobalValue::ExternalLinkage, 0, "CURRENT_SAMPLE");
	this->CURRENT_SAMPLE->setAlignment(8);
	this->CURRENT_SAMPLE->setInitializer(this->ConstantLong0);


	//"SAMPLE_RATE" string
	ArrayType* ArrayTy12 = ArrayType::get(IntegerType::get(pModule->getContext(), 8), 12);
	GlobalVariable * pArrayStr = new GlobalVariable(*pModule, ArrayTy12, true, GlobalValue::PrivateLinkage, 0, "");
	pArrayStr->setAlignment(1);  
	Constant * ConstArray = ConstantDataArray::getString(pModule->getContext(), "SAMPLE_RATE", true);
	vector<Constant *> vecIndex;
	vecIndex.push_back(this->ConstantInt0); 
	vecIndex.push_back(this->ConstantInt0);
	this->SAMPLE_RATE_ptr = ConstantExpr::getGetElementPtr(pArrayStr, vecIndex);
	pArrayStr->setInitializer(ConstArray);

	//""
	ArrayType * ArrayTy17 = ArrayType::get(IntegerType::get(pModule->getContext(), 8), 17);
	pArrayStr = new GlobalVariable(*pModule, ArrayTy17, true, GlobalValue::PrivateLinkage, 0, "");
	pArrayStr->setAlignment(1);
	ConstArray = ConstantDataArray::getString(pModule->getContext(), "SAMPLE_RATE: %d\x0A", true);
	vecIndex.clear();
	vecIndex.push_back(this->ConstantInt0);
	vecIndex.push_back(this->ConstantInt0);
	this->Output_Format_String = ConstantExpr::getGetElementPtr(pArrayStr, vecIndex);
	pArrayStr->setInitializer(ConstArray);	
}
开发者ID:songlh,项目名称:LDoctor,代码行数:51,代码来源:WLInstrument.cpp

示例2: unsetFifo

void Connection::unsetFifo(){
    //Get GV of the port
    GlobalVariable* srcVar = srcPort->getFifoVar();
    GlobalVariable* dstVar = tgtPort->getFifoVar();

    //Remove GV initializer
    srcVar->setInitializer(NULL);
    dstVar->setInitializer(NULL);

    //Delete the fifo
    if (fifo != NULL){
        delete fifo;
        fifo = NULL;
    }
}
开发者ID:orcc,项目名称:jade,代码行数:15,代码来源:Connection.cpp

示例3: assert

static GlobalVariable *getAiVar(Function &F, const CallInst *CI) {
  const ConstantExpr *GEP =
    dyn_cast<const ConstantExpr>(CI->getOperand(1));
  assert(GEP && GEP->getOpcode() == Instruction::GetElementPtr);
  const GlobalVariable *strVar =
    dyn_cast<const GlobalVariable>(GEP->getOperand(0));
  assert(strVar && strVar->hasInitializer());
  const ConstantDataArray *str =
    dyn_cast<const ConstantDataArray>(strVar->getInitializer());
  assert(str && str->isCString());
  std::string id = str->getAsCString();
  char *cstr = new char[11 + id.size() + 1];
  strcpy(cstr, "__ai_state_"); /* len=11 */
  strcpy(cstr + 11, id.c_str());
  for (size_t i = 11; i < 11 + id.size(); i++)
    if (cstr[i] != '_' && !isupper(cstr[i]) && !islower(cstr[i]))
      cstr[i] = 'X';
  Type *intType = TypeBuilder<int, false>::get(F.getContext());
  GlobalVariable *glob =
    dyn_cast<GlobalVariable>(F.getParent()->getOrInsertGlobal(cstr, intType));
  delete cstr;
  glob->setInitializer(ConstantInt::get(
                            TypeBuilder<int, false>::get(F.getContext()), 0));
  return glob;
}
开发者ID:RedlineResearch,项目名称:LLVMSlicer,代码行数:25,代码来源:Prepare.cpp

示例4: jl_emit_and_add_to_shadow

// global variables to pointers are pretty common,
// so this method is available as a convenience for emitting them.
// for other types, the formula for implementation is straightforward:
// (see stringConstPtr, for an alternative example to the code below)
//
// if in imaging_mode, emit a GlobalVariable with the same name and an initializer to the shadow_module
// making it valid for emission and reloading in the sysimage
//
// then add a global mapping to the current value (usually from calloc'd space)
// to the execution engine to make it valid for the current session (with the current value)
void* jl_emit_and_add_to_shadow(GlobalVariable *gv, void *gvarinit)
{
    PointerType *T = cast<PointerType>(gv->getType()->getElementType()); // pointer is the only supported type here

    GlobalVariable *shadowvar = NULL;
#if defined(USE_MCJIT) || defined(USE_ORCJIT)
    if (imaging_mode)
#endif
        shadowvar = global_proto(gv, shadow_output);

    if (shadowvar) {
        shadowvar->setInitializer(ConstantPointerNull::get(T));
        shadowvar->setLinkage(GlobalVariable::InternalLinkage);
        addComdat(shadowvar);
        if (imaging_mode && gvarinit) {
            // make the pointer valid for future sessions
            jl_sysimg_gvars.push_back(ConstantExpr::getBitCast(shadowvar, T_psize));
            jl_value_llvm gv_struct;
            gv_struct.gv = global_proto(gv);
            gv_struct.index = jl_sysimg_gvars.size();
            jl_value_to_llvm[gvarinit] = gv_struct;
        }
    }

    // make the pointer valid for this session
#if defined(USE_MCJIT) || defined(USE_ORCJIT)
    void *slot = calloc(1, sizeof(void*));
    jl_ExecutionEngine->addGlobalMapping(gv, slot);
    return slot;
#else
    return jl_ExecutionEngine->getPointerToGlobal(shadowvar);
#endif
}
开发者ID:Dangyl1992,项目名称:julia,代码行数:43,代码来源:jitlayers.cpp

示例5: handleAsm

bool Prepare::handleAsm(Function &F, CallInst *CI) {
  const InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
  std::string ASM = IA->getAsmString();
  std::string CONS = IA->getConstraintString();

//  BasicBlock *BB = CI->getParent();

  if ((ASM.empty() && !CI->getNumArgOperands()) || /* a barrier */
      !ASM.compare(0, 6, "1:\tud2") ||
      !ASM.compare("lfence") || !ASM.compare("mfence") ||
      !ASM.compare("sfence")) {
/*    errs() << ASM << " (" << F.getName() << "): " << ASM.empty() << " " << !ASM.compare(0, 6, "1:\tud2") << " " <<
      !ASM.compare("lfence") << " " << !ASM.compare("mfence") << " " <<
      !ASM.compare("sfence");
    BB->dump();*/
    CI->eraseFromParent();
    return true;
  } else if (ASM.empty() && CI->getNumArgOperands() == 1) { /* reloc hide */
    ReplaceInstWithInst(CI, CastInst::CreatePointerCast(CI->getArgOperand(0),
                                                        CI->getType()));
    return true;
  } else if (!ASM.compare("movs %gs:${1:c},$0") || /* reading pda */
             !ASM.compare("movl %gs:${1:c},$0") ||
             !ASM.compare("movq %gs:${1:c},$0")) {
    const ConstantInt *param = dyn_cast<ConstantInt>(CI->getArgOperand(0));
    if (param) {
      const APInt &paramVal = param->getValue();
      Module *M = F.getParent();
      if (paramVal == 0) { /* current */
        ReplaceInstWithInst(CI, new LoadInst(
                                  M->getOrInsertGlobal("__ai_current_singleton",
                                                       CI->getType())));
        return true;
      } else { /* others, let's fake it with global var */
        GlobalVariable *GV = dyn_cast<GlobalVariable>(
              M->getOrInsertGlobal("__ai_pda_" + paramVal.toString(10, false),
                                   CI->getType()));
        GV->setInitializer(Constant::getNullValue(CI->getType()));
        if (CI->getType()->isPointerTy())
          errs() << "Warn ptr type => we set it to point to NULL\n";
        ReplaceInstWithInst(CI, new LoadInst(GV));
        return true;
      }
    }
  } else if (!ASM.compare(0, 16, "call __put_user_") ||
             !ASM.compare(0, 16, "call __get_user_") ) {
    BasicBlock::iterator it(CI);
    ReplaceInstWithValue(CI->getParent()->getInstList(), it,
                         Constant::getNullValue(CI->getType()));
    return true;
  }
  errs() << "ASM str (" << F.getName() << "): " << ASM << " from:\n";
  CI->dump();
  errs() << "===========\n";
  return false;
}
开发者ID:RedlineResearch,项目名称:LLVMSlicer,代码行数:56,代码来源:Prepare.cpp

示例6: addTableDataSection

static bool addTableDataSection(NativeModulePtr natMod, 
        Module *M, VA &newVA, const T& table)
{

    list<DataSection>  &globaldata = natMod->getData();
    list<DataSection>::const_iterator git = globaldata.begin();

    // ensure we make this the last data section
    newVA = 0;
    while( git != globaldata.end() ) {
        const DataSection         &dt = *git;
        uint64_t extent = dt.getBase() + dt.getSize();
        if(newVA < extent) {
            newVA = extent;
        }
        git++;
    }

    // skip a few
    newVA += 4;

    // create a new data section from the table
    DataSection *ds = tableToDataSection(newVA, table);
    
    // add to global data section list
    globaldata.push_back(*ds);

    // create the GlobalVariable
    string bufferName = "data_0x" + to_string<VA>(newVA, hex);
    StructType *st_opaque = StructType::create(M->getContext());
    GlobalVariable *gv = new GlobalVariable(*M,
                            st_opaque, 
                            true,
                            GlobalVariable::InternalLinkage,
                            NULL,
                            bufferName);

    vector<Type*> data_section_types;
    vector<Constant*>    secContents;

    dataSectionToTypesContents(globaldata, 
            *ds, 
            M, 
            secContents, 
            data_section_types, 
            false);

    st_opaque->setBody(data_section_types, true);
    Constant *cst = ConstantStruct::get(st_opaque, secContents);
    gv->setAlignment(4);
    gv->setInitializer(cst);

    return true;

} 
开发者ID:Sineaggi,项目名称:mcsema,代码行数:55,代码来源:JumpTables.cpp

示例7: SP

 virtual Value * materializeValueFor(Value * V) {
     if(Function * fn = dyn_cast<Function>(V)) {
         assert(fn->getParent() == src);
         Function * newfn = dest->getFunction(fn->getName());
         if(!newfn) {
             newfn = Function::Create(fn->getFunctionType(),fn->getLinkage(), fn->getName(),dest);
             newfn->copyAttributesFrom(fn);
         }
         if(!fn->isDeclaration() && newfn->isDeclaration() && copyGlobal(fn,data)) {
             for(Function::arg_iterator II = newfn->arg_begin(), I = fn->arg_begin(), E = fn->arg_end(); I != E; ++I, ++II) {
                 II->setName(I->getName());
                 VMap[I] = II;
             }
             VMap[fn] = newfn;
             SmallVector<ReturnInst*,8> Returns;
             CloneFunctionInto(newfn, fn, VMap, true, Returns, "", NULL, NULL, this);
         }
         return newfn;
     } else if(GlobalVariable * GV = dyn_cast<GlobalVariable>(V)) {
         GlobalVariable * newGV = dest->getGlobalVariable(GV->getName(),true);
         if(!newGV) {
             newGV = new GlobalVariable(*dest,GV->getType()->getElementType(),GV->isConstant(),GV->getLinkage(),NULL,GV->getName(),NULL,GlobalVariable::NotThreadLocal,GV->getType()->getAddressSpace());
             newGV->copyAttributesFrom(GV);
             if(!GV->isDeclaration()) {
                 if(!copyGlobal(GV,data)) {
                     newGV->setExternallyInitialized(true);
                 } else if(GV->hasInitializer()) {
                     Value * C = MapValue(GV->getInitializer(),VMap,RF_None,NULL,this);
                     newGV->setInitializer(cast<Constant>(C));
                 }
             }
         }
         return newGV;
     } else if(MDNode * MD = dyn_cast<MDNode>(V)) {
         DISubprogram SP(MD);
         if(DI != NULL && SP.isSubprogram()) {
             
             if(Function * OF = SP.getFunction()) {
                 Function * F = cast<Function>(MapValue(OF,VMap,RF_None,NULL,this));
                 DISubprogram NSP = DI->createFunction(SP.getContext(), SP.getName(), SP.getLinkageName(),
                                                   DI->createFile(SP.getFilename(),SP.getDirectory()),
                                                   SP.getLineNumber(), SP.getType(),
                                                   SP.isLocalToUnit(), SP.isDefinition(),
                                                   SP.getScopeLineNumber(),SP.getFlags(),SP.isOptimized(),
                                                   F);
                 return NSP;
             }
             /* fallthrough */
         }
         /* fallthrough */
     }
     return NULL;
 }
开发者ID:0----0,项目名称:terra,代码行数:53,代码来源:tllvmutil.cpp

示例8: addAddress

void StorageSoa::addAddress(int idx)
{
   GlobalVariable *val = new GlobalVariable(
      /*Type=*/IntegerType::get(32),
      /*isConstant=*/false,
      /*Linkage=*/GlobalValue::ExternalLinkage,
      /*Initializer=*/0, // has initializer, specified below
      /*Name=*/name("address"),
      currentModule());
   val->setInitializer(Constant::getNullValue(IntegerType::get(32)));

   debug_printf("adding to %d\n", idx);
   m_addresses[idx] = val;
}
开发者ID:smowton,项目名称:vgallium,代码行数:14,代码来源:storagesoa.cpp

示例9: linkGlobalInits

// linkGlobalInits - Update the initializers in the Dest module now that all
// globals that may be referenced are in Dest.
void ModuleLinker::linkGlobalInits() {
  // Loop over all of the globals in the src module, mapping them over as we go
  for (Module::const_global_iterator I = SrcM->global_begin(),
       E = SrcM->global_end(); I != E; ++I) {
    
    // Only process initialized GV's or ones not already in dest.
    if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;          
    
    // Grab destination global variable.
    GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
    // Figure out what the initializer looks like in the dest module.
    DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
                                 RF_None, &TypeMap));
  }
}
开发者ID:groue,项目名称:llvm,代码行数:17,代码来源:LinkModules.cpp

示例10: runOnFunction

  bool runOnFunction(Function &F) override
  {
    if (F.hasFnAttribute("emit_llvm")) {
      Module *M = F.getParent();

      static Regex R("4func.*$");
      GlobalVariable *GV = M->getGlobalVariable(R.sub("2irE", F.getName()), true);
      if (GV != NULL) {
        string S;
        raw_string_ostream SO(S);
        F.print(SO);

        Constant *CDA = ConstantDataArray::getString(M->getContext(), SO.str());
        GV->setInitializer(ConstantExpr::getBitCast(new GlobalVariable(*M, CDA->getType(), true, GV->getLinkage(), CDA),
                                                    Type::getInt8PtrTy(M->getContext())));

        return true;
      }
    }

    return false;
  }
开发者ID:cpcloud,项目名称:libdynd,代码行数:22,代码来源:dynd.cpp

示例11: mapAppendingVariable

void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
                                  bool IsOldCtorDtor,
                                  ArrayRef<Constant *> NewMembers) {
  SmallVector<Constant *, 16> Elements;
  if (InitPrefix) {
    unsigned NumElements =
        cast<ArrayType>(InitPrefix->getType())->getNumElements();
    for (unsigned I = 0; I != NumElements; ++I)
      Elements.push_back(InitPrefix->getAggregateElement(I));
  }

  PointerType *VoidPtrTy;
  Type *EltTy;
  if (IsOldCtorDtor) {
    // FIXME: This upgrade is done during linking to support the C API.  See
    // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
    VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
    auto &ST = *cast<StructType>(NewMembers.front()->getType());
    Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
    EltTy = StructType::get(GV.getContext(), Tys, false);
  }

  for (auto *V : NewMembers) {
    Constant *NewV;
    if (IsOldCtorDtor) {
      auto *S = cast<ConstantStruct>(V);
      auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
      auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
      Constant *Null = Constant::getNullValue(VoidPtrTy);
      NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null);
    } else {
      NewV = cast_or_null<Constant>(mapValue(V));
    }
    Elements.push_back(NewV);
  }

  GV.setInitializer(ConstantArray::get(
      cast<ArrayType>(GV.getType()->getElementType()), Elements));
}
开发者ID:BNieuwenhuizen,项目名称:llvm,代码行数:39,代码来源:ValueMapper.cpp

示例12: InsertProfilingShutdownCall

void llvm::InsertProfilingShutdownCall(Function *Callee, Module *Mod) {
  // llvm.global_dtors is an array of type { i32, void ()* }. Prepare those
  // types.
  Type *GlobalDtorElems[2] = {
    Type::getInt32Ty(Mod->getContext()),
    FunctionType::get(Type::getVoidTy(Mod->getContext()), false)->getPointerTo()
  };
  StructType *GlobalDtorElemTy =
      StructType::get(Mod->getContext(), GlobalDtorElems, false);

  // Construct the new element we'll be adding.
  Constant *Elem[2] = {
    ConstantInt::get(Type::getInt32Ty(Mod->getContext()), 65535),
    ConstantExpr::getBitCast(Callee, GlobalDtorElems[1])
  };

  // If llvm.global_dtors exists, make a copy of the things in its list and
  // delete it, to replace it with one that has a larger array type.
  std::vector<Constant *> dtors;
  if (GlobalVariable *GlobalDtors = Mod->getNamedGlobal("llvm.global_dtors")) {
    if (ConstantArray *InitList =
        dyn_cast<ConstantArray>(GlobalDtors->getInitializer())) {
      for (unsigned i = 0, e = InitList->getType()->getNumElements();
           i != e; ++i)
        dtors.push_back(cast<Constant>(InitList->getOperand(i)));
    }
    GlobalDtors->eraseFromParent();
  }

  // Build up llvm.global_dtors with our new item in it.
  GlobalVariable *GlobalDtors = new GlobalVariable(
      *Mod, ArrayType::get(GlobalDtorElemTy, 1), false,
      GlobalValue::AppendingLinkage, NULL, "llvm.global_dtors");
                                    
  dtors.push_back(ConstantStruct::get(GlobalDtorElemTy, Elem));
  GlobalDtors->setInitializer(ConstantArray::get(
      cast<ArrayType>(GlobalDtors->getType()->getElementType()), dtors));
}
开发者ID:UIKit0,项目名称:LLVM_IRProfiling,代码行数:38,代码来源:ProfilingUtils.cpp

示例13: DASSERT

llvm::Constant * CodeGenerator::genGlobalVar(const VariableDefn * var) {
  // Global variables never set the IRValue field, because that field has a different value
  // depending on what module we are compiling.
  DASSERT(var->defnType() == Defn::Var);
  DASSERT(var->irValue() == NULL);
  DASSERT(var->storageClass() == Storage_Global || var->storageClass() == Storage_Static);

  DASSERT_OBJ(var->passes().isFinished(VariableDefn::InitializerPass), var);

  GlobalVariable * gv = irModule_->getGlobalVariable(var->linkageName());
  if (gv != NULL) {
    return gv;
  }

  const Type * varType = var->type().unqualified();
  DASSERT(varType != NULL);

  // Create the global variable
  GlobalValue::LinkageTypes linkType = Function::ExternalLinkage;
  if (var->isSynthetic()) {
    linkType = Function::LinkOnceAnyLinkage;
  }

  // The reason that this is irType instead of irEmbeddedType is because LLVM always turns
  // the type of a global variable into a pointer anyway.
  llvm::Type * irType = varType->irEmbeddedType();
  gv = new GlobalVariable(*irModule_, irType, false, linkType, NULL, var->linkageName(),
      NULL, var->isThreadLocal());

  // Only supply an initialization expression if the variable was
  // defined in this module - otherwise, it's an external declaration.
  if (var->module() == module_ || var->isSynthetic()) {
    addStaticRoot(gv, varType);
    if (debug_) {
      genDIGlobalVariable(var, gv);
    }

    // If it has an initialization expression
    const Expr * initExpr = var->initValue();
    if (initExpr != NULL) {
      if (initExpr->isConstant()) {
        Constant * initValue = genConstExpr(initExpr);
        if (initValue == NULL) {
          return NULL;
        }

        if (varType->isReferenceType()) {
          initValue = new GlobalVariable(
              *irModule_, initValue->getType(), false, linkType, initValue,
              var->linkageName() + ".init");
          initValue = llvm::ConstantExpr::getPointerCast(initValue, varType->irEmbeddedType());
        }

        gv->setInitializer(initValue);
      } else {
        genModuleInitFunc();

        // Add it to the module init function
        BasicBlock * savePoint = builder_.GetInsertBlock();
        builder_.SetInsertPoint(moduleInitBlock_);

        // Generate the expression.
        Value * initValue = genExpr(initExpr);
        if (initValue != NULL) {
          gv->setInitializer(llvm::Constant::getNullValue(irType));
          builder_.CreateStore(initValue, gv);
        }

        if (savePoint != NULL) {
          builder_.SetInsertPoint(savePoint);
        }
      }
    } else if (!var->isExtern()) {
      // No initializer, so set the value to zerofill.
      gv->setInitializer(llvm::Constant::getNullValue(irType));
    }
  }

  return gv;
}
开发者ID:afrog33k,项目名称:tart,代码行数:80,代码来源:CodeGenDefn.cpp

示例14: addEmuTlsVar

bool LowerEmuTLS::addEmuTlsVar(Module &M, const GlobalVariable *GV) {
  LLVMContext &C = M.getContext();
  PointerType *VoidPtrType = Type::getInt8PtrTy(C);

  std::string EmuTlsVarName = ("__emutls_v." + GV->getName()).str();
  GlobalVariable *EmuTlsVar = M.getNamedGlobal(EmuTlsVarName);
  if (EmuTlsVar)
    return false;  // It has been added before.

  const DataLayout &DL = M.getDataLayout();
  Constant *NullPtr = ConstantPointerNull::get(VoidPtrType);

  // Get non-zero initializer from GV's initializer.
  const Constant *InitValue = nullptr;
  if (GV->hasInitializer()) {
    InitValue = GV->getInitializer();
    const ConstantInt *InitIntValue = dyn_cast<ConstantInt>(InitValue);
    // When GV's init value is all 0, omit the EmuTlsTmplVar and let
    // the emutls library function to reset newly allocated TLS variables.
    if (isa<ConstantAggregateZero>(InitValue) ||
        (InitIntValue && InitIntValue->isZero()))
      InitValue = nullptr;
  }

  // Create the __emutls_v. symbol, whose type has 4 fields:
  //     word size;   // size of GV in bytes
  //     word align;  // alignment of GV
  //     void *ptr;   // initialized to 0; set at run time per thread.
  //     void *templ; // 0 or point to __emutls_t.*
  // sizeof(word) should be the same as sizeof(void*) on target.
  IntegerType *WordType = DL.getIntPtrType(C);
  PointerType *InitPtrType = InitValue ?
      PointerType::getUnqual(InitValue->getType()) : VoidPtrType;
  Type *ElementTypes[4] = {WordType, WordType, VoidPtrType, InitPtrType};
  ArrayRef<Type*> ElementTypeArray(ElementTypes, 4);
  StructType *EmuTlsVarType = StructType::create(ElementTypeArray);
  EmuTlsVar = cast<GlobalVariable>(
      M.getOrInsertGlobal(EmuTlsVarName, EmuTlsVarType));
  copyLinkageVisibility(M, GV, EmuTlsVar);

  // Define "__emutls_t.*" and "__emutls_v.*" only if GV is defined.
  if (!GV->hasInitializer())
    return true;

  Type *GVType = GV->getValueType();
  unsigned GVAlignment = GV->getAlignment();
  if (!GVAlignment) {
    // When LLVM IL declares a variable without alignment, use
    // the ABI default alignment for the type.
    GVAlignment = DL.getABITypeAlignment(GVType);
  }

  // Define "__emutls_t.*" if there is InitValue
  GlobalVariable *EmuTlsTmplVar = nullptr;
  if (InitValue) {
    std::string EmuTlsTmplName = ("__emutls_t." + GV->getName()).str();
    EmuTlsTmplVar = dyn_cast_or_null<GlobalVariable>(
        M.getOrInsertGlobal(EmuTlsTmplName, GVType));
    assert(EmuTlsTmplVar && "Failed to create emualted TLS initializer");
    EmuTlsTmplVar->setConstant(true);
    EmuTlsTmplVar->setInitializer(const_cast<Constant*>(InitValue));
    EmuTlsTmplVar->setAlignment(GVAlignment);
    copyLinkageVisibility(M, GV, EmuTlsTmplVar);
  }

  // Define "__emutls_v.*" with initializer and alignment.
  Constant *ElementValues[4] = {
      ConstantInt::get(WordType, DL.getTypeStoreSize(GVType)),
      ConstantInt::get(WordType, GVAlignment),
      NullPtr, EmuTlsTmplVar ? EmuTlsTmplVar : NullPtr
  };
  ArrayRef<Constant*> ElementValueArray(ElementValues, 4);
  EmuTlsVar->setInitializer(
      ConstantStruct::get(EmuTlsVarType, ElementValueArray));
  unsigned MaxAlignment = std::max(
      DL.getABITypeAlignment(WordType),
      DL.getABITypeAlignment(VoidPtrType));
  EmuTlsVar->setAlignment(MaxAlignment);
  return true;
}
开发者ID:szrambo,项目名称:llvm,代码行数:80,代码来源:LowerEmuTLS.cpp

示例15: GlobalVariable

std::unique_ptr<Module> llvm::CloneModule(
    const Module *M, ValueToValueMapTy &VMap,
    std::function<bool(const GlobalValue *)> ShouldCloneDefinition) {
  // First off, we need to create the new module.
  std::unique_ptr<Module> New =
      llvm::make_unique<Module>(M->getModuleIdentifier(), M->getContext());
  New->setDataLayout(M->getDataLayout());
  New->setTargetTriple(M->getTargetTriple());
  New->setModuleInlineAsm(M->getModuleInlineAsm());
   
  // Loop over all of the global variables, making corresponding globals in the
  // new module.  Here we add them to the VMap and to the new Module.  We
  // don't worry about attributes or initializers, they will come later.
  //
  for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
       I != E; ++I) {
    GlobalVariable *GV = new GlobalVariable(*New, 
                                            I->getValueType(),
                                            I->isConstant(), I->getLinkage(),
                                            (Constant*) nullptr, I->getName(),
                                            (GlobalVariable*) nullptr,
                                            I->getThreadLocalMode(),
                                            I->getType()->getAddressSpace());
    GV->copyAttributesFrom(&*I);
    VMap[&*I] = GV;
  }

  // Loop over the functions in the module, making external functions as before
  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
    Function *NF =
        Function::Create(cast<FunctionType>(I->getValueType()),
                         I->getLinkage(), I->getName(), New.get());
    NF->copyAttributesFrom(&*I);
    VMap[&*I] = NF;
  }

  // Loop over the aliases in the module
  for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
       I != E; ++I) {
    if (!ShouldCloneDefinition(&*I)) {
      // An alias cannot act as an external reference, so we need to create
      // either a function or a global variable depending on the value type.
      // FIXME: Once pointee types are gone we can probably pick one or the
      // other.
      GlobalValue *GV;
      if (I->getValueType()->isFunctionTy())
        GV = Function::Create(cast<FunctionType>(I->getValueType()),
                              GlobalValue::ExternalLinkage, I->getName(),
                              New.get());
      else
        GV = new GlobalVariable(
            *New, I->getValueType(), false, GlobalValue::ExternalLinkage,
            (Constant *)nullptr, I->getName(), (GlobalVariable *)nullptr,
            I->getThreadLocalMode(), I->getType()->getAddressSpace());
      VMap[&*I] = GV;
      // We do not copy attributes (mainly because copying between different
      // kinds of globals is forbidden), but this is generally not required for
      // correctness.
      continue;
    }
    auto *GA = GlobalAlias::create(I->getValueType(),
                                   I->getType()->getPointerAddressSpace(),
                                   I->getLinkage(), I->getName(), New.get());
    GA->copyAttributesFrom(&*I);
    VMap[&*I] = GA;
  }
  
  // Now that all of the things that global variable initializer can refer to
  // have been created, loop through and copy the global variable referrers
  // over...  We also set the attributes on the global now.
  //
  for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
       I != E; ++I) {
    GlobalVariable *GV = cast<GlobalVariable>(VMap[&*I]);
    if (!ShouldCloneDefinition(&*I)) {
      // Skip after setting the correct linkage for an external reference.
      GV->setLinkage(GlobalValue::ExternalLinkage);
      continue;
    }
    if (I->hasInitializer())
      GV->setInitializer(MapValue(I->getInitializer(), VMap));
  }

  // Similarly, copy over function bodies now...
  //
  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
    Function *F = cast<Function>(VMap[&*I]);
    if (!ShouldCloneDefinition(&*I)) {
      // Skip after setting the correct linkage for an external reference.
      F->setLinkage(GlobalValue::ExternalLinkage);
      // Personality function is not valid on a declaration.
      F->setPersonalityFn(nullptr);
      continue;
    }
    if (!I->isDeclaration()) {
      Function::arg_iterator DestI = F->arg_begin();
      for (Function::const_arg_iterator J = I->arg_begin(); J != I->arg_end();
           ++J) {
        DestI->setName(J->getName());
        VMap[&*J] = &*DestI++;
//.........这里部分代码省略.........
开发者ID:flyingGH,项目名称:llvm,代码行数:101,代码来源:CloneModule.cpp


注:本文中的GlobalVariable::setInitializer方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。