+// EmitGlobal - Choose the right section for global and emit it
+void ELFWriter::EmitGlobal(const GlobalValue *GV) {
+
+ // Handle ELF Bind, Visibility and Type for the current symbol
+ unsigned SymBind = getGlobalELFBinding(GV);
+ ELFSym *GblSym = new ELFSym(GV);
+ GblSym->setBind(SymBind);
+ GblSym->setVisibility(getGlobalELFVisibility(GV));
+ GblSym->setType(getGlobalELFType(GV));
+
+ if (isELFUndefSym(GV)) {
+ GblSym->SectionIdx = ELFSection::SHN_UNDEF;
+ } else {
+ assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
+ const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
+
+ // Get ELF section from TAI
+ const Section *S = TAI->SectionForGlobal(GV);
+ unsigned SectionFlags = getElfSectionFlags(S->getFlags());
+
+ // The symbol align should update the section alignment if needed
+ const TargetData *TD = TM.getTargetData();
+ unsigned Align = TD->getPreferredAlignment(GVar);
+ unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
+ GblSym->Size = Size;
+
+ if (isELFCommonSym(GV)) {
+ GblSym->SectionIdx = ELFSection::SHN_COMMON;
+ getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags, 1);
+
+ // A new linkonce section is created for each global in the
+ // common section, the default alignment is 1 and the symbol
+ // value contains its alignment.
+ GblSym->Value = Align;
+
+ } else if (isELFBssSym(GV)) {
+ ELFSection &ES =
+ getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags);
+ GblSym->SectionIdx = ES.SectionIdx;
+
+ // Update the size with alignment and the next object can
+ // start in the right offset in the section
+ if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
+ ES.Align = std::max(ES.Align, Align);
+
+ // GblSym->Value should contain the virtual offset inside the section.
+ // Virtual because the BSS space is not allocated on ELF objects
+ GblSym->Value = ES.Size;
+ ES.Size += Size;
+
+ } else if (isELFDataSym(GV)) {
+ ELFSection &ES =
+ getSection(S->getName(), ELFSection::SHT_PROGBITS, SectionFlags);
+ GblSym->SectionIdx = ES.SectionIdx;
+
+ // GblSym->Value should contain the symbol offset inside the section,
+ // and all symbols should start on their required alignment boundary
+ ES.Align = std::max(ES.Align, Align);
+ GblSym->Value = (ES.size() + (Align-1)) & (-Align);
+ ES.emitAlignment(ES.Align);
+
+ // Emit the global to the data section 'ES'
+ EmitGlobalConstant(GVar->getInitializer(), ES);
+ }