AsmPrinter.cpp revision 693cfcc5b58cedcedd2701064ef6a17d13275b83
1//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the AsmPrinter class. 11// 12//===----------------------------------------------------------------------===// 13 14#include "llvm/CodeGen/AsmPrinter.h" 15#include "llvm/Assembly/Writer.h" 16#include "llvm/DerivedTypes.h" 17#include "llvm/Constants.h" 18#include "llvm/Module.h" 19#include "llvm/CodeGen/GCMetadataPrinter.h" 20#include "llvm/CodeGen/MachineConstantPool.h" 21#include "llvm/CodeGen/MachineJumpTableInfo.h" 22#include "llvm/CodeGen/MachineModuleInfo.h" 23#include "llvm/CodeGen/DwarfWriter.h" 24#include "llvm/Analysis/DebugInfo.h" 25#include "llvm/MC/MCContext.h" 26#include "llvm/MC/MCInst.h" 27#include "llvm/MC/MCSection.h" 28#include "llvm/MC/MCStreamer.h" 29#include "llvm/Support/CommandLine.h" 30#include "llvm/Support/ErrorHandling.h" 31#include "llvm/Support/FormattedStream.h" 32#include "llvm/Support/Mangler.h" 33#include "llvm/Target/TargetAsmInfo.h" 34#include "llvm/Target/TargetData.h" 35#include "llvm/Target/TargetLowering.h" 36#include "llvm/Target/TargetLoweringObjectFile.h" 37#include "llvm/Target/TargetOptions.h" 38#include "llvm/Target/TargetRegisterInfo.h" 39#include "llvm/ADT/SmallPtrSet.h" 40#include "llvm/ADT/SmallString.h" 41#include "llvm/ADT/StringExtras.h" 42#include <cerrno> 43using namespace llvm; 44 45static cl::opt<cl::boolOrDefault> 46AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 47 cl::init(cl::BOU_UNSET)); 48 49char AsmPrinter::ID = 0; 50AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm, 51 const TargetAsmInfo *T, bool VDef) 52 : MachineFunctionPass(&ID), FunctionNumber(0), O(o), 53 TM(tm), TAI(T), TRI(tm.getRegisterInfo()), 54 55 OutContext(*new MCContext()), 56 OutStreamer(*createAsmStreamer(OutContext, O)), 57 58 LastMI(0), LastFn(0), Counter(~0U), 59 PrevDLT(0, ~0U, ~0U) { 60 CurrentSection = 0; 61 DW = 0; MMI = 0; 62 switch (AsmVerbose) { 63 case cl::BOU_UNSET: VerboseAsm = VDef; break; 64 case cl::BOU_TRUE: VerboseAsm = true; break; 65 case cl::BOU_FALSE: VerboseAsm = false; break; 66 } 67} 68 69AsmPrinter::~AsmPrinter() { 70 for (gcp_iterator I = GCMetadataPrinters.begin(), 71 E = GCMetadataPrinters.end(); I != E; ++I) 72 delete I->second; 73 74 delete &OutStreamer; 75 delete &OutContext; 76} 77 78TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 79 return TM.getTargetLowering()->getObjFileLowering(); 80} 81 82/// SwitchToSection - Switch to the specified section of the executable if we 83/// are not already in it! If "NS" is null, then this causes us to exit the 84/// current section and not reenter another one. This is generally used for 85/// asmprinter hacks. 86/// 87/// FIXME: Remove support for null sections. 88/// 89void AsmPrinter::SwitchToSection(const MCSection *NS) { 90 // If we're already in this section, we're done. 91 if (CurrentSection == NS) return; 92 93 CurrentSection = NS; 94 95 if (NS != 0) { 96 // If section is named we need to switch into it via special '.section' 97 // directive and also append funky flags. Otherwise - section name is just 98 // some magic assembler directive. 99 if (!NS->isDirective()) { 100 SmallString<32> FlagsStr; 101 102 getObjFileLowering().getSectionFlagsAsString(NS->getKind(), FlagsStr); 103 104 O << TAI->getSwitchToSectionDirective() 105 << CurrentSection->getName() << FlagsStr.c_str(); 106 } else { 107 O << CurrentSection->getName(); 108 } 109 O << TAI->getDataSectionStartSuffix() << '\n'; 110 } 111} 112 113void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 114 AU.setPreservesAll(); 115 MachineFunctionPass::getAnalysisUsage(AU); 116 AU.addRequired<GCModuleInfo>(); 117} 118 119bool AsmPrinter::doInitialization(Module &M) { 120 // Initialize TargetLoweringObjectFile. 121 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 122 .Initialize(OutContext, TM); 123 124 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix(), 125 TAI->getLinkerPrivateGlobalPrefix()); 126 127 if (TAI->doesAllowQuotesInName()) 128 Mang->setUseQuotes(true); 129 130 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 131 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 132 133 if (TAI->hasSingleParameterDotFile()) { 134 /* Very minimal debug info. It is ignored if we emit actual 135 debug info. If we don't, this at helps the user find where 136 a function came from. */ 137 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n"; 138 } 139 140 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I) 141 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 142 MP->beginAssembly(O, *this, *TAI); 143 144 if (!M.getModuleInlineAsm().empty()) 145 O << TAI->getCommentString() << " Start of file scope inline assembly\n" 146 << M.getModuleInlineAsm() 147 << '\n' << TAI->getCommentString() 148 << " End of file scope inline assembly\n"; 149 150 SwitchToSection(0); // Reset back to no section to close off sections. 151 152 if (TAI->doesSupportDebugInformation() || 153 TAI->doesSupportExceptionHandling()) { 154 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 155 if (MMI) 156 MMI->AnalyzeModule(M); 157 DW = getAnalysisIfAvailable<DwarfWriter>(); 158 if (DW) 159 DW->BeginModule(&M, MMI, O, this, TAI); 160 } 161 162 return false; 163} 164 165bool AsmPrinter::doFinalization(Module &M) { 166 // Emit global variables. 167 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 168 I != E; ++I) 169 PrintGlobalVariable(I); 170 171 // Emit final debug information. 172 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling()) 173 DW->EndModule(); 174 175 // If the target wants to know about weak references, print them all. 176 if (TAI->getWeakRefDirective()) { 177 // FIXME: This is not lazy, it would be nice to only print weak references 178 // to stuff that is actually used. Note that doing so would require targets 179 // to notice uses in operands (due to constant exprs etc). This should 180 // happen with the MC stuff eventually. 181 SwitchToSection(0); 182 183 // Print out module-level global variables here. 184 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 185 I != E; ++I) { 186 if (I->hasExternalWeakLinkage()) 187 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n'; 188 } 189 190 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 191 if (I->hasExternalWeakLinkage()) 192 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n'; 193 } 194 } 195 196 if (TAI->getSetDirective()) { 197 O << '\n'; 198 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 199 I != E; ++I) { 200 std::string Name = Mang->getMangledName(I); 201 202 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal()); 203 std::string Target = Mang->getMangledName(GV); 204 205 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective()) 206 O << "\t.globl\t" << Name << '\n'; 207 else if (I->hasWeakLinkage()) 208 O << TAI->getWeakRefDirective() << Name << '\n'; 209 else if (!I->hasLocalLinkage()) 210 llvm_unreachable("Invalid alias linkage"); 211 212 printVisibility(Name, I->getVisibility()); 213 214 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n'; 215 } 216 } 217 218 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 219 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 220 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 221 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I)) 222 MP->finishAssembly(O, *this, *TAI); 223 224 // If we don't have any trampolines, then we don't require stack memory 225 // to be executable. Some targets have a directive to declare this. 226 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 227 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 228 if (TAI->getNonexecutableStackDirective()) 229 O << TAI->getNonexecutableStackDirective() << '\n'; 230 231 delete Mang; Mang = 0; 232 DW = 0; MMI = 0; 233 234 OutStreamer.Finish(); 235 return false; 236} 237 238std::string 239AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const { 240 assert(MF && "No machine function?"); 241 return Mang->getMangledName(MF->getFunction(), ".eh", 242 TAI->is_EHSymbolPrivate()); 243} 244 245void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 246 // What's my mangled name? 247 CurrentFnName = Mang->getMangledName(MF.getFunction()); 248 IncrementFunctionNumber(); 249} 250 251namespace { 252 // SectionCPs - Keep track the alignment, constpool entries per Section. 253 struct SectionCPs { 254 const MCSection *S; 255 unsigned Alignment; 256 SmallVector<unsigned, 4> CPEs; 257 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}; 258 }; 259} 260 261/// EmitConstantPool - Print to the current output stream assembly 262/// representations of the constants in the constant pool MCP. This is 263/// used to print out constants which have been "spilled to memory" by 264/// the code generator. 265/// 266void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) { 267 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 268 if (CP.empty()) return; 269 270 // Calculate sections for constant pool entries. We collect entries to go into 271 // the same section together to reduce amount of section switch statements. 272 SmallVector<SectionCPs, 4> CPSections; 273 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 274 const MachineConstantPoolEntry &CPE = CP[i]; 275 unsigned Align = CPE.getAlignment(); 276 277 SectionKind Kind; 278 switch (CPE.getRelocationInfo()) { 279 default: llvm_unreachable("Unknown section kind"); 280 case 2: Kind = SectionKind::getReadOnlyWithRel(); break; 281 case 1: 282 Kind = SectionKind::getReadOnlyWithRelLocal(); 283 break; 284 case 0: 285 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) { 286 case 4: Kind = SectionKind::getMergeableConst4(); break; 287 case 8: Kind = SectionKind::getMergeableConst8(); break; 288 case 16: Kind = SectionKind::getMergeableConst16();break; 289 default: Kind = SectionKind::getMergeableConst(); break; 290 } 291 } 292 293 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind); 294 295 // The number of sections are small, just do a linear search from the 296 // last section to the first. 297 bool Found = false; 298 unsigned SecIdx = CPSections.size(); 299 while (SecIdx != 0) { 300 if (CPSections[--SecIdx].S == S) { 301 Found = true; 302 break; 303 } 304 } 305 if (!Found) { 306 SecIdx = CPSections.size(); 307 CPSections.push_back(SectionCPs(S, Align)); 308 } 309 310 if (Align > CPSections[SecIdx].Alignment) 311 CPSections[SecIdx].Alignment = Align; 312 CPSections[SecIdx].CPEs.push_back(i); 313 } 314 315 // Now print stuff into the calculated sections. 316 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 317 SwitchToSection(CPSections[i].S); 318 EmitAlignment(Log2_32(CPSections[i].Alignment)); 319 320 unsigned Offset = 0; 321 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 322 unsigned CPI = CPSections[i].CPEs[j]; 323 MachineConstantPoolEntry CPE = CP[CPI]; 324 325 // Emit inter-object padding for alignment. 326 unsigned AlignMask = CPE.getAlignment() - 1; 327 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 328 EmitZeros(NewOffset - Offset); 329 330 const Type *Ty = CPE.getType(); 331 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty); 332 333 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_' 334 << CPI << ":\t\t\t\t\t"; 335 if (VerboseAsm) { 336 O << TAI->getCommentString() << ' '; 337 WriteTypeSymbolic(O, CPE.getType(), 0); 338 } 339 O << '\n'; 340 if (CPE.isMachineConstantPoolEntry()) 341 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 342 else 343 EmitGlobalConstant(CPE.Val.ConstVal); 344 } 345 } 346} 347 348/// EmitJumpTableInfo - Print assembly representations of the jump tables used 349/// by the current function to the current output stream. 350/// 351void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI, 352 MachineFunction &MF) { 353 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 354 if (JT.empty()) return; 355 356 bool IsPic = TM.getRelocationModel() == Reloc::PIC_; 357 358 // Pick the directive to use to print the jump table entries, and switch to 359 // the appropriate section. 360 TargetLowering *LoweringInfo = TM.getTargetLowering(); 361 362 const Function *F = MF.getFunction(); 363 bool JTInDiffSection = false; 364 if (F->isWeakForLinker() || 365 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) { 366 // In PIC mode, we need to emit the jump table to the same section as the 367 // function body itself, otherwise the label differences won't make sense. 368 // We should also do if the section name is NULL or function is declared in 369 // discardable section. 370 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM)); 371 } else { 372 // Otherwise, drop it in the readonly section. 373 const MCSection *ReadOnlySection = 374 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly()); 375 SwitchToSection(ReadOnlySection); 376 JTInDiffSection = true; 377 } 378 379 EmitAlignment(Log2_32(MJTI->getAlignment())); 380 381 for (unsigned i = 0, e = JT.size(); i != e; ++i) { 382 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs; 383 384 // If this jump table was deleted, ignore it. 385 if (JTBBs.empty()) continue; 386 387 // For PIC codegen, if possible we want to use the SetDirective to reduce 388 // the number of relocations the assembler will generate for the jump table. 389 // Set directives are all printed before the jump table itself. 390 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets; 391 if (TAI->getSetDirective() && IsPic) 392 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 393 if (EmittedSets.insert(JTBBs[ii])) 394 printPICJumpTableSetLabel(i, JTBBs[ii]); 395 396 // On some targets (e.g. darwin) we want to emit two consequtive labels 397 // before each jump table. The first label is never referenced, but tells 398 // the assembler and linker the extents of the jump table object. The 399 // second label is actually referenced by the code. 400 if (JTInDiffSection) { 401 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix()) 402 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n"; 403 } 404 405 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 406 << '_' << i << ":\n"; 407 408 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 409 printPICJumpTableEntry(MJTI, JTBBs[ii], i); 410 O << '\n'; 411 } 412 } 413} 414 415void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI, 416 const MachineBasicBlock *MBB, 417 unsigned uid) const { 418 bool IsPic = TM.getRelocationModel() == Reloc::PIC_; 419 420 // Use JumpTableDirective otherwise honor the entry size from the jump table 421 // info. 422 const char *JTEntryDirective = TAI->getJumpTableDirective(); 423 bool HadJTEntryDirective = JTEntryDirective != NULL; 424 if (!HadJTEntryDirective) { 425 JTEntryDirective = MJTI->getEntrySize() == 4 ? 426 TAI->getData32bitsDirective() : TAI->getData64bitsDirective(); 427 } 428 429 O << JTEntryDirective << ' '; 430 431 // If we have emitted set directives for the jump table entries, print 432 // them rather than the entries themselves. If we're emitting PIC, then 433 // emit the table entries as differences between two text section labels. 434 // If we're emitting non-PIC code, then emit the entries as direct 435 // references to the target basic blocks. 436 if (IsPic) { 437 if (TAI->getSetDirective()) { 438 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber() 439 << '_' << uid << "_set_" << MBB->getNumber(); 440 } else { 441 printBasicBlockLabel(MBB, false, false, false); 442 // If the arch uses custom Jump Table directives, don't calc relative to 443 // JT 444 if (!HadJTEntryDirective) 445 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" 446 << getFunctionNumber() << '_' << uid; 447 } 448 } else { 449 printBasicBlockLabel(MBB, false, false, false); 450 } 451} 452 453 454/// EmitSpecialLLVMGlobal - Check to see if the specified global is a 455/// special global used by LLVM. If so, emit it and return true, otherwise 456/// do nothing and return false. 457bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 458 if (GV->getName() == "llvm.used") { 459 if (TAI->getUsedDirective() != 0) // No need to emit this at all. 460 EmitLLVMUsedList(GV->getInitializer()); 461 return true; 462 } 463 464 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 465 if (GV->getSection() == "llvm.metadata" || 466 GV->hasAvailableExternallyLinkage()) 467 return true; 468 469 if (!GV->hasAppendingLinkage()) return false; 470 471 assert(GV->hasInitializer() && "Not a special LLVM global!"); 472 473 const TargetData *TD = TM.getTargetData(); 474 unsigned Align = Log2_32(TD->getPointerPrefAlignment()); 475 if (GV->getName() == "llvm.global_ctors") { 476 SwitchToSection(getObjFileLowering().getStaticCtorSection()); 477 EmitAlignment(Align, 0); 478 EmitXXStructorList(GV->getInitializer()); 479 return true; 480 } 481 482 if (GV->getName() == "llvm.global_dtors") { 483 SwitchToSection(getObjFileLowering().getStaticDtorSection()); 484 EmitAlignment(Align, 0); 485 EmitXXStructorList(GV->getInitializer()); 486 return true; 487 } 488 489 return false; 490} 491 492/// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each 493/// global in the specified llvm.used list for which emitUsedDirectiveFor 494/// is true, as being used with this directive. 495void AsmPrinter::EmitLLVMUsedList(Constant *List) { 496 const char *Directive = TAI->getUsedDirective(); 497 498 // Should be an array of 'i8*'. 499 ConstantArray *InitList = dyn_cast<ConstantArray>(List); 500 if (InitList == 0) return; 501 502 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 503 const GlobalValue *GV = 504 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 505 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) { 506 O << Directive; 507 EmitConstantValueOnly(InitList->getOperand(i)); 508 O << '\n'; 509 } 510 } 511} 512 513/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the 514/// function pointers, ignoring the init priority. 515void AsmPrinter::EmitXXStructorList(Constant *List) { 516 // Should be an array of '{ int, void ()* }' structs. The first value is the 517 // init priority, which we ignore. 518 if (!isa<ConstantArray>(List)) return; 519 ConstantArray *InitList = cast<ConstantArray>(List); 520 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 521 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){ 522 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 523 524 if (CS->getOperand(1)->isNullValue()) 525 return; // Found a null terminator, exit printing. 526 // Emit the function pointer. 527 EmitGlobalConstant(CS->getOperand(1)); 528 } 529} 530 531/// getGlobalLinkName - Returns the asm/link name of of the specified 532/// global variable. Should be overridden by each target asm printer to 533/// generate the appropriate value. 534const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV, 535 std::string &LinkName) const { 536 if (isa<Function>(GV)) { 537 LinkName += TAI->getFunctionAddrPrefix(); 538 LinkName += Mang->getMangledName(GV); 539 LinkName += TAI->getFunctionAddrSuffix(); 540 } else { 541 LinkName += TAI->getGlobalVarAddrPrefix(); 542 LinkName += Mang->getMangledName(GV); 543 LinkName += TAI->getGlobalVarAddrSuffix(); 544 } 545 546 return LinkName; 547} 548 549/// EmitExternalGlobal - Emit the external reference to a global variable. 550/// Should be overridden if an indirect reference should be used. 551void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) { 552 std::string GLN; 553 O << getGlobalLinkName(GV, GLN); 554} 555 556 557 558//===----------------------------------------------------------------------===// 559/// LEB 128 number encoding. 560 561/// PrintULEB128 - Print a series of hexidecimal values (separated by commas) 562/// representing an unsigned leb128 value. 563void AsmPrinter::PrintULEB128(unsigned Value) const { 564 char Buffer[20]; 565 do { 566 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); 567 Value >>= 7; 568 if (Value) Byte |= 0x80; 569 O << "0x" << utohex_buffer(Byte, Buffer+20); 570 if (Value) O << ", "; 571 } while (Value); 572} 573 574/// PrintSLEB128 - Print a series of hexidecimal values (separated by commas) 575/// representing a signed leb128 value. 576void AsmPrinter::PrintSLEB128(int Value) const { 577 int Sign = Value >> (8 * sizeof(Value) - 1); 578 bool IsMore; 579 char Buffer[20]; 580 581 do { 582 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); 583 Value >>= 7; 584 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; 585 if (IsMore) Byte |= 0x80; 586 O << "0x" << utohex_buffer(Byte, Buffer+20); 587 if (IsMore) O << ", "; 588 } while (IsMore); 589} 590 591//===--------------------------------------------------------------------===// 592// Emission and print routines 593// 594 595/// PrintHex - Print a value as a hexidecimal value. 596/// 597void AsmPrinter::PrintHex(int Value) const { 598 char Buffer[20]; 599 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20); 600} 601 602/// EOL - Print a newline character to asm stream. If a comment is present 603/// then it will be printed first. Comments should not contain '\n'. 604void AsmPrinter::EOL() const { 605 O << '\n'; 606} 607 608void AsmPrinter::EOL(const std::string &Comment) const { 609 if (VerboseAsm && !Comment.empty()) { 610 O << '\t' 611 << TAI->getCommentString() 612 << ' ' 613 << Comment; 614 } 615 O << '\n'; 616} 617 618void AsmPrinter::EOL(const char* Comment) const { 619 if (VerboseAsm && *Comment) { 620 O << '\t' 621 << TAI->getCommentString() 622 << ' ' 623 << Comment; 624 } 625 O << '\n'; 626} 627 628/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an 629/// unsigned leb128 value. 630void AsmPrinter::EmitULEB128Bytes(unsigned Value) const { 631 if (TAI->hasLEB128()) { 632 O << "\t.uleb128\t" 633 << Value; 634 } else { 635 O << TAI->getData8bitsDirective(); 636 PrintULEB128(Value); 637 } 638} 639 640/// EmitSLEB128Bytes - print an assembler byte data directive to compose a 641/// signed leb128 value. 642void AsmPrinter::EmitSLEB128Bytes(int Value) const { 643 if (TAI->hasLEB128()) { 644 O << "\t.sleb128\t" 645 << Value; 646 } else { 647 O << TAI->getData8bitsDirective(); 648 PrintSLEB128(Value); 649 } 650} 651 652/// EmitInt8 - Emit a byte directive and value. 653/// 654void AsmPrinter::EmitInt8(int Value) const { 655 O << TAI->getData8bitsDirective(); 656 PrintHex(Value & 0xFF); 657} 658 659/// EmitInt16 - Emit a short directive and value. 660/// 661void AsmPrinter::EmitInt16(int Value) const { 662 O << TAI->getData16bitsDirective(); 663 PrintHex(Value & 0xFFFF); 664} 665 666/// EmitInt32 - Emit a long directive and value. 667/// 668void AsmPrinter::EmitInt32(int Value) const { 669 O << TAI->getData32bitsDirective(); 670 PrintHex(Value); 671} 672 673/// EmitInt64 - Emit a long long directive and value. 674/// 675void AsmPrinter::EmitInt64(uint64_t Value) const { 676 if (TAI->getData64bitsDirective()) { 677 O << TAI->getData64bitsDirective(); 678 PrintHex(Value); 679 } else { 680 if (TM.getTargetData()->isBigEndian()) { 681 EmitInt32(unsigned(Value >> 32)); O << '\n'; 682 EmitInt32(unsigned(Value)); 683 } else { 684 EmitInt32(unsigned(Value)); O << '\n'; 685 EmitInt32(unsigned(Value >> 32)); 686 } 687 } 688} 689 690/// toOctal - Convert the low order bits of X into an octal digit. 691/// 692static inline char toOctal(int X) { 693 return (X&7)+'0'; 694} 695 696/// printStringChar - Print a char, escaped if necessary. 697/// 698static void printStringChar(formatted_raw_ostream &O, unsigned char C) { 699 if (C == '"') { 700 O << "\\\""; 701 } else if (C == '\\') { 702 O << "\\\\"; 703 } else if (isprint((unsigned char)C)) { 704 O << C; 705 } else { 706 switch(C) { 707 case '\b': O << "\\b"; break; 708 case '\f': O << "\\f"; break; 709 case '\n': O << "\\n"; break; 710 case '\r': O << "\\r"; break; 711 case '\t': O << "\\t"; break; 712 default: 713 O << '\\'; 714 O << toOctal(C >> 6); 715 O << toOctal(C >> 3); 716 O << toOctal(C >> 0); 717 break; 718 } 719 } 720} 721 722/// EmitString - Emit a string with quotes and a null terminator. 723/// Special characters are emitted properly. 724/// \literal (Eg. '\t') \endliteral 725void AsmPrinter::EmitString(const std::string &String) const { 726 EmitString(String.c_str(), String.size()); 727} 728 729void AsmPrinter::EmitString(const char *String, unsigned Size) const { 730 const char* AscizDirective = TAI->getAscizDirective(); 731 if (AscizDirective) 732 O << AscizDirective; 733 else 734 O << TAI->getAsciiDirective(); 735 O << '\"'; 736 for (unsigned i = 0; i < Size; ++i) 737 printStringChar(O, String[i]); 738 if (AscizDirective) 739 O << '\"'; 740 else 741 O << "\\0\""; 742} 743 744 745/// EmitFile - Emit a .file directive. 746void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const { 747 O << "\t.file\t" << Number << " \""; 748 for (unsigned i = 0, N = Name.size(); i < N; ++i) 749 printStringChar(O, Name[i]); 750 O << '\"'; 751} 752 753 754//===----------------------------------------------------------------------===// 755 756// EmitAlignment - Emit an alignment directive to the specified power of 757// two boundary. For example, if you pass in 3 here, you will get an 8 758// byte alignment. If a global value is specified, and if that global has 759// an explicit alignment requested, it will unconditionally override the 760// alignment request. However, if ForcedAlignBits is specified, this value 761// has final say: the ultimate alignment will be the max of ForcedAlignBits 762// and the alignment computed with NumBits and the global. 763// 764// The algorithm is: 765// Align = NumBits; 766// if (GV && GV->hasalignment) Align = GV->getalignment(); 767// Align = std::max(Align, ForcedAlignBits); 768// 769void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV, 770 unsigned ForcedAlignBits, 771 bool UseFillExpr) const { 772 if (GV && GV->getAlignment()) 773 NumBits = Log2_32(GV->getAlignment()); 774 NumBits = std::max(NumBits, ForcedAlignBits); 775 776 if (NumBits == 0) return; // No need to emit alignment. 777 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits; 778 O << TAI->getAlignDirective() << NumBits; 779 780 if (CurrentSection && CurrentSection->getKind().isText()) 781 if (unsigned FillValue = TAI->getTextAlignFillValue()) { 782 O << ','; 783 PrintHex(FillValue); 784 } 785 O << '\n'; 786} 787 788/// PadToColumn - This gets called every time a tab is emitted. If 789/// column padding is turned on, we replace the tab with the 790/// appropriate amount of padding. If not, we replace the tab with a 791/// space, except for the first operand so that initial operands are 792/// always lined up by tabs. 793void AsmPrinter::PadToColumn(unsigned Operand) const { 794 if (TAI->getOperandColumn(Operand) > 0) { 795 O.PadToColumn(TAI->getOperandColumn(Operand), 1); 796 } 797 else { 798 if (Operand == 1) { 799 // Emit the tab after the mnemonic. 800 O << '\t'; 801 } 802 else { 803 // Replace the tab with a space. 804 O << ' '; 805 } 806 } 807} 808 809/// EmitZeros - Emit a block of zeros. 810/// 811void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const { 812 if (NumZeros) { 813 if (TAI->getZeroDirective()) { 814 O << TAI->getZeroDirective() << NumZeros; 815 if (TAI->getZeroDirectiveSuffix()) 816 O << TAI->getZeroDirectiveSuffix(); 817 O << '\n'; 818 } else { 819 for (; NumZeros; --NumZeros) 820 O << TAI->getData8bitsDirective(AddrSpace) << "0\n"; 821 } 822 } 823} 824 825// Print out the specified constant, without a storage class. Only the 826// constants valid in constant expressions can occur here. 827void AsmPrinter::EmitConstantValueOnly(const Constant *CV) { 828 if (CV->isNullValue() || isa<UndefValue>(CV)) 829 O << '0'; 830 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 831 O << CI->getZExtValue(); 832 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) { 833 // This is a constant address for a global variable or function. Use the 834 // name of the variable or function as the address value, possibly 835 // decorating it with GlobalVarAddrPrefix/Suffix or 836 // FunctionAddrPrefix/Suffix (these all default to "" ) 837 if (isa<Function>(GV)) { 838 O << TAI->getFunctionAddrPrefix() 839 << Mang->getMangledName(GV) 840 << TAI->getFunctionAddrSuffix(); 841 } else { 842 O << TAI->getGlobalVarAddrPrefix() 843 << Mang->getMangledName(GV) 844 << TAI->getGlobalVarAddrSuffix(); 845 } 846 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 847 const TargetData *TD = TM.getTargetData(); 848 unsigned Opcode = CE->getOpcode(); 849 switch (Opcode) { 850 case Instruction::Trunc: 851 case Instruction::ZExt: 852 case Instruction::SExt: 853 case Instruction::FPTrunc: 854 case Instruction::FPExt: 855 case Instruction::UIToFP: 856 case Instruction::SIToFP: 857 case Instruction::FPToUI: 858 case Instruction::FPToSI: 859 llvm_unreachable("FIXME: Don't support this constant cast expr"); 860 case Instruction::GetElementPtr: { 861 // generate a symbolic expression for the byte address 862 const Constant *ptrVal = CE->getOperand(0); 863 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end()); 864 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0], 865 idxVec.size())) { 866 // Truncate/sext the offset to the pointer size. 867 if (TD->getPointerSizeInBits() != 64) { 868 int SExtAmount = 64-TD->getPointerSizeInBits(); 869 Offset = (Offset << SExtAmount) >> SExtAmount; 870 } 871 872 if (Offset) 873 O << '('; 874 EmitConstantValueOnly(ptrVal); 875 if (Offset > 0) 876 O << ") + " << Offset; 877 else if (Offset < 0) 878 O << ") - " << -Offset; 879 } else { 880 EmitConstantValueOnly(ptrVal); 881 } 882 break; 883 } 884 case Instruction::BitCast: 885 return EmitConstantValueOnly(CE->getOperand(0)); 886 887 case Instruction::IntToPtr: { 888 // Handle casts to pointers by changing them into casts to the appropriate 889 // integer type. This promotes constant folding and simplifies this code. 890 Constant *Op = CE->getOperand(0); 891 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/); 892 return EmitConstantValueOnly(Op); 893 } 894 895 896 case Instruction::PtrToInt: { 897 // Support only foldable casts to/from pointers that can be eliminated by 898 // changing the pointer to the appropriately sized integer type. 899 Constant *Op = CE->getOperand(0); 900 const Type *Ty = CE->getType(); 901 902 // We can emit the pointer value into this slot if the slot is an 903 // integer slot greater or equal to the size of the pointer. 904 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType())) 905 return EmitConstantValueOnly(Op); 906 907 O << "(("; 908 EmitConstantValueOnly(Op); 909 APInt ptrMask = 910 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType())); 911 912 SmallString<40> S; 913 ptrMask.toStringUnsigned(S); 914 O << ") & " << S.c_str() << ')'; 915 break; 916 } 917 case Instruction::Add: 918 case Instruction::Sub: 919 case Instruction::And: 920 case Instruction::Or: 921 case Instruction::Xor: 922 O << '('; 923 EmitConstantValueOnly(CE->getOperand(0)); 924 O << ')'; 925 switch (Opcode) { 926 case Instruction::Add: 927 O << " + "; 928 break; 929 case Instruction::Sub: 930 O << " - "; 931 break; 932 case Instruction::And: 933 O << " & "; 934 break; 935 case Instruction::Or: 936 O << " | "; 937 break; 938 case Instruction::Xor: 939 O << " ^ "; 940 break; 941 default: 942 break; 943 } 944 O << '('; 945 EmitConstantValueOnly(CE->getOperand(1)); 946 O << ')'; 947 break; 948 default: 949 llvm_unreachable("Unsupported operator!"); 950 } 951 } else { 952 llvm_unreachable("Unknown constant value!"); 953 } 954} 955 956/// printAsCString - Print the specified array as a C compatible string, only if 957/// the predicate isString is true. 958/// 959static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA, 960 unsigned LastElt) { 961 assert(CVA->isString() && "Array is not string compatible!"); 962 963 O << '\"'; 964 for (unsigned i = 0; i != LastElt; ++i) { 965 unsigned char C = 966 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue(); 967 printStringChar(O, C); 968 } 969 O << '\"'; 970} 971 972/// EmitString - Emit a zero-byte-terminated string constant. 973/// 974void AsmPrinter::EmitString(const ConstantArray *CVA) const { 975 unsigned NumElts = CVA->getNumOperands(); 976 if (TAI->getAscizDirective() && NumElts && 977 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) { 978 O << TAI->getAscizDirective(); 979 printAsCString(O, CVA, NumElts-1); 980 } else { 981 O << TAI->getAsciiDirective(); 982 printAsCString(O, CVA, NumElts); 983 } 984 O << '\n'; 985} 986 987void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA, 988 unsigned AddrSpace) { 989 if (CVA->isString()) { 990 EmitString(CVA); 991 } else { // Not a string. Print the values in successive locations 992 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i) 993 EmitGlobalConstant(CVA->getOperand(i), AddrSpace); 994 } 995} 996 997void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) { 998 const VectorType *PTy = CP->getType(); 999 1000 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I) 1001 EmitGlobalConstant(CP->getOperand(I)); 1002} 1003 1004void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS, 1005 unsigned AddrSpace) { 1006 // Print the fields in successive locations. Pad to align if needed! 1007 const TargetData *TD = TM.getTargetData(); 1008 unsigned Size = TD->getTypeAllocSize(CVS->getType()); 1009 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType()); 1010 uint64_t sizeSoFar = 0; 1011 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) { 1012 const Constant* field = CVS->getOperand(i); 1013 1014 // Check if padding is needed and insert one or more 0s. 1015 uint64_t fieldSize = TD->getTypeAllocSize(field->getType()); 1016 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1)) 1017 - cvsLayout->getElementOffset(i)) - fieldSize; 1018 sizeSoFar += fieldSize + padSize; 1019 1020 // Now print the actual field value. 1021 EmitGlobalConstant(field, AddrSpace); 1022 1023 // Insert padding - this may include padding to increase the size of the 1024 // current field up to the ABI size (if the struct is not packed) as well 1025 // as padding to ensure that the next field starts at the right offset. 1026 EmitZeros(padSize, AddrSpace); 1027 } 1028 assert(sizeSoFar == cvsLayout->getSizeInBytes() && 1029 "Layout of constant struct may be incorrect!"); 1030} 1031 1032void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP, 1033 unsigned AddrSpace) { 1034 // FP Constants are printed as integer constants to avoid losing 1035 // precision... 1036 const TargetData *TD = TM.getTargetData(); 1037 if (CFP->getType() == Type::DoubleTy) { 1038 double Val = CFP->getValueAPF().convertToDouble(); // for comment only 1039 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1040 if (TAI->getData64bitsDirective(AddrSpace)) { 1041 O << TAI->getData64bitsDirective(AddrSpace) << i; 1042 if (VerboseAsm) 1043 O << '\t' << TAI->getCommentString() << " double value: " << Val; 1044 O << '\n'; 1045 } else if (TD->isBigEndian()) { 1046 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32); 1047 if (VerboseAsm) 1048 O << '\t' << TAI->getCommentString() 1049 << " double most significant word " << Val; 1050 O << '\n'; 1051 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i); 1052 if (VerboseAsm) 1053 O << '\t' << TAI->getCommentString() 1054 << " double least significant word " << Val; 1055 O << '\n'; 1056 } else { 1057 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i); 1058 if (VerboseAsm) 1059 O << '\t' << TAI->getCommentString() 1060 << " double least significant word " << Val; 1061 O << '\n'; 1062 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32); 1063 if (VerboseAsm) 1064 O << '\t' << TAI->getCommentString() 1065 << " double most significant word " << Val; 1066 O << '\n'; 1067 } 1068 return; 1069 } else if (CFP->getType() == Type::FloatTy) { 1070 float Val = CFP->getValueAPF().convertToFloat(); // for comment only 1071 O << TAI->getData32bitsDirective(AddrSpace) 1072 << CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1073 if (VerboseAsm) 1074 O << '\t' << TAI->getCommentString() << " float " << Val; 1075 O << '\n'; 1076 return; 1077 } else if (CFP->getType() == Type::X86_FP80Ty) { 1078 // all long double variants are printed as hex 1079 // api needed to prevent premature destruction 1080 APInt api = CFP->getValueAPF().bitcastToAPInt(); 1081 const uint64_t *p = api.getRawData(); 1082 // Convert to double so we can print the approximate val as a comment. 1083 APFloat DoubleVal = CFP->getValueAPF(); 1084 bool ignored; 1085 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 1086 &ignored); 1087 if (TD->isBigEndian()) { 1088 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]); 1089 if (VerboseAsm) 1090 O << '\t' << TAI->getCommentString() 1091 << " long double most significant halfword of ~" 1092 << DoubleVal.convertToDouble(); 1093 O << '\n'; 1094 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48); 1095 if (VerboseAsm) 1096 O << '\t' << TAI->getCommentString() << " long double next halfword"; 1097 O << '\n'; 1098 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32); 1099 if (VerboseAsm) 1100 O << '\t' << TAI->getCommentString() << " long double next halfword"; 1101 O << '\n'; 1102 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16); 1103 if (VerboseAsm) 1104 O << '\t' << TAI->getCommentString() << " long double next halfword"; 1105 O << '\n'; 1106 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]); 1107 if (VerboseAsm) 1108 O << '\t' << TAI->getCommentString() 1109 << " long double least significant halfword"; 1110 O << '\n'; 1111 } else { 1112 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]); 1113 if (VerboseAsm) 1114 O << '\t' << TAI->getCommentString() 1115 << " long double least significant halfword of ~" 1116 << DoubleVal.convertToDouble(); 1117 O << '\n'; 1118 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16); 1119 if (VerboseAsm) 1120 O << '\t' << TAI->getCommentString() 1121 << " long double next halfword"; 1122 O << '\n'; 1123 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32); 1124 if (VerboseAsm) 1125 O << '\t' << TAI->getCommentString() 1126 << " long double next halfword"; 1127 O << '\n'; 1128 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48); 1129 if (VerboseAsm) 1130 O << '\t' << TAI->getCommentString() 1131 << " long double next halfword"; 1132 O << '\n'; 1133 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]); 1134 if (VerboseAsm) 1135 O << '\t' << TAI->getCommentString() 1136 << " long double most significant halfword"; 1137 O << '\n'; 1138 } 1139 EmitZeros(TD->getTypeAllocSize(Type::X86_FP80Ty) - 1140 TD->getTypeStoreSize(Type::X86_FP80Ty), AddrSpace); 1141 return; 1142 } else if (CFP->getType() == Type::PPC_FP128Ty) { 1143 // all long double variants are printed as hex 1144 // api needed to prevent premature destruction 1145 APInt api = CFP->getValueAPF().bitcastToAPInt(); 1146 const uint64_t *p = api.getRawData(); 1147 if (TD->isBigEndian()) { 1148 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32); 1149 if (VerboseAsm) 1150 O << '\t' << TAI->getCommentString() 1151 << " long double most significant word"; 1152 O << '\n'; 1153 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]); 1154 if (VerboseAsm) 1155 O << '\t' << TAI->getCommentString() 1156 << " long double next word"; 1157 O << '\n'; 1158 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32); 1159 if (VerboseAsm) 1160 O << '\t' << TAI->getCommentString() 1161 << " long double next word"; 1162 O << '\n'; 1163 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]); 1164 if (VerboseAsm) 1165 O << '\t' << TAI->getCommentString() 1166 << " long double least significant word"; 1167 O << '\n'; 1168 } else { 1169 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]); 1170 if (VerboseAsm) 1171 O << '\t' << TAI->getCommentString() 1172 << " long double least significant word"; 1173 O << '\n'; 1174 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32); 1175 if (VerboseAsm) 1176 O << '\t' << TAI->getCommentString() 1177 << " long double next word"; 1178 O << '\n'; 1179 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]); 1180 if (VerboseAsm) 1181 O << '\t' << TAI->getCommentString() 1182 << " long double next word"; 1183 O << '\n'; 1184 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32); 1185 if (VerboseAsm) 1186 O << '\t' << TAI->getCommentString() 1187 << " long double most significant word"; 1188 O << '\n'; 1189 } 1190 return; 1191 } else llvm_unreachable("Floating point constant type not handled"); 1192} 1193 1194void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI, 1195 unsigned AddrSpace) { 1196 const TargetData *TD = TM.getTargetData(); 1197 unsigned BitWidth = CI->getBitWidth(); 1198 assert(isPowerOf2_32(BitWidth) && 1199 "Non-power-of-2-sized integers not handled!"); 1200 1201 // We don't expect assemblers to support integer data directives 1202 // for more than 64 bits, so we emit the data in at most 64-bit 1203 // quantities at a time. 1204 const uint64_t *RawData = CI->getValue().getRawData(); 1205 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 1206 uint64_t Val; 1207 if (TD->isBigEndian()) 1208 Val = RawData[e - i - 1]; 1209 else 1210 Val = RawData[i]; 1211 1212 if (TAI->getData64bitsDirective(AddrSpace)) 1213 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n'; 1214 else if (TD->isBigEndian()) { 1215 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32); 1216 if (VerboseAsm) 1217 O << '\t' << TAI->getCommentString() 1218 << " Double-word most significant word " << Val; 1219 O << '\n'; 1220 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val); 1221 if (VerboseAsm) 1222 O << '\t' << TAI->getCommentString() 1223 << " Double-word least significant word " << Val; 1224 O << '\n'; 1225 } else { 1226 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val); 1227 if (VerboseAsm) 1228 O << '\t' << TAI->getCommentString() 1229 << " Double-word least significant word " << Val; 1230 O << '\n'; 1231 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32); 1232 if (VerboseAsm) 1233 O << '\t' << TAI->getCommentString() 1234 << " Double-word most significant word " << Val; 1235 O << '\n'; 1236 } 1237 } 1238} 1239 1240/// EmitGlobalConstant - Print a general LLVM constant to the .s file. 1241void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) { 1242 const TargetData *TD = TM.getTargetData(); 1243 const Type *type = CV->getType(); 1244 unsigned Size = TD->getTypeAllocSize(type); 1245 1246 if (CV->isNullValue() || isa<UndefValue>(CV)) { 1247 EmitZeros(Size, AddrSpace); 1248 return; 1249 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) { 1250 EmitGlobalConstantArray(CVA , AddrSpace); 1251 return; 1252 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) { 1253 EmitGlobalConstantStruct(CVS, AddrSpace); 1254 return; 1255 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 1256 EmitGlobalConstantFP(CFP, AddrSpace); 1257 return; 1258 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1259 // Small integers are handled below; large integers are handled here. 1260 if (Size > 4) { 1261 EmitGlobalConstantLargeInt(CI, AddrSpace); 1262 return; 1263 } 1264 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 1265 EmitGlobalConstantVector(CP); 1266 return; 1267 } 1268 1269 printDataDirective(type, AddrSpace); 1270 EmitConstantValueOnly(CV); 1271 if (VerboseAsm) { 1272 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1273 SmallString<40> S; 1274 CI->getValue().toStringUnsigned(S, 16); 1275 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str(); 1276 } 1277 } 1278 O << '\n'; 1279} 1280 1281void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 1282 // Target doesn't support this yet! 1283 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 1284} 1285 1286/// PrintSpecial - Print information related to the specified machine instr 1287/// that is independent of the operand, and may be independent of the instr 1288/// itself. This can be useful for portably encoding the comment character 1289/// or other bits of target-specific knowledge into the asmstrings. The 1290/// syntax used is ${:comment}. Targets can override this to add support 1291/// for their own strange codes. 1292void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const { 1293 if (!strcmp(Code, "private")) { 1294 O << TAI->getPrivateGlobalPrefix(); 1295 } else if (!strcmp(Code, "comment")) { 1296 if (VerboseAsm) 1297 O << TAI->getCommentString(); 1298 } else if (!strcmp(Code, "uid")) { 1299 // Comparing the address of MI isn't sufficient, because machineinstrs may 1300 // be allocated to the same address across functions. 1301 const Function *ThisF = MI->getParent()->getParent()->getFunction(); 1302 1303 // If this is a new LastFn instruction, bump the counter. 1304 if (LastMI != MI || LastFn != ThisF) { 1305 ++Counter; 1306 LastMI = MI; 1307 LastFn = ThisF; 1308 } 1309 O << Counter; 1310 } else { 1311 std::string msg; 1312 raw_string_ostream Msg(msg); 1313 Msg << "Unknown special formatter '" << Code 1314 << "' for machine instr: " << *MI; 1315 llvm_report_error(Msg.str()); 1316 } 1317} 1318 1319/// processDebugLoc - Processes the debug information of each machine 1320/// instruction's DebugLoc. 1321void AsmPrinter::processDebugLoc(DebugLoc DL) { 1322 if (!TAI || !DW) 1323 return; 1324 1325 if (TAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) { 1326 if (!DL.isUnknown()) { 1327 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL); 1328 1329 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) 1330 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col, 1331 DICompileUnit(CurDLT.CompileUnit))); 1332 1333 PrevDLT = CurDLT; 1334 } 1335 } 1336} 1337 1338/// printInlineAsm - This method formats and prints the specified machine 1339/// instruction that is an inline asm. 1340void AsmPrinter::printInlineAsm(const MachineInstr *MI) const { 1341 unsigned NumOperands = MI->getNumOperands(); 1342 1343 // Count the number of register definitions. 1344 unsigned NumDefs = 0; 1345 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); 1346 ++NumDefs) 1347 assert(NumDefs != NumOperands-1 && "No asm string?"); 1348 1349 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?"); 1350 1351 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc. 1352 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); 1353 1354 // If this asmstr is empty, just print the #APP/#NOAPP markers. 1355 // These are useful to see where empty asm's wound up. 1356 if (AsmStr[0] == 0) { 1357 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n'; 1358 return; 1359 } 1360 1361 O << TAI->getInlineAsmStart() << "\n\t"; 1362 1363 // The variant of the current asmprinter. 1364 int AsmPrinterVariant = TAI->getAssemblerDialect(); 1365 1366 int CurVariant = -1; // The number of the {.|.|.} region we are in. 1367 const char *LastEmitted = AsmStr; // One past the last character emitted. 1368 1369 while (*LastEmitted) { 1370 switch (*LastEmitted) { 1371 default: { 1372 // Not a special case, emit the string section literally. 1373 const char *LiteralEnd = LastEmitted+1; 1374 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && 1375 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') 1376 ++LiteralEnd; 1377 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1378 O.write(LastEmitted, LiteralEnd-LastEmitted); 1379 LastEmitted = LiteralEnd; 1380 break; 1381 } 1382 case '\n': 1383 ++LastEmitted; // Consume newline character. 1384 O << '\n'; // Indent code with newline. 1385 break; 1386 case '$': { 1387 ++LastEmitted; // Consume '$' character. 1388 bool Done = true; 1389 1390 // Handle escapes. 1391 switch (*LastEmitted) { 1392 default: Done = false; break; 1393 case '$': // $$ -> $ 1394 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1395 O << '$'; 1396 ++LastEmitted; // Consume second '$' character. 1397 break; 1398 case '(': // $( -> same as GCC's { character. 1399 ++LastEmitted; // Consume '(' character. 1400 if (CurVariant != -1) { 1401 llvm_report_error("Nested variants found in inline asm string: '" 1402 + std::string(AsmStr) + "'"); 1403 } 1404 CurVariant = 0; // We're in the first variant now. 1405 break; 1406 case '|': 1407 ++LastEmitted; // consume '|' character. 1408 if (CurVariant == -1) 1409 O << '|'; // this is gcc's behavior for | outside a variant 1410 else 1411 ++CurVariant; // We're in the next variant. 1412 break; 1413 case ')': // $) -> same as GCC's } char. 1414 ++LastEmitted; // consume ')' character. 1415 if (CurVariant == -1) 1416 O << '}'; // this is gcc's behavior for } outside a variant 1417 else 1418 CurVariant = -1; 1419 break; 1420 } 1421 if (Done) break; 1422 1423 bool HasCurlyBraces = false; 1424 if (*LastEmitted == '{') { // ${variable} 1425 ++LastEmitted; // Consume '{' character. 1426 HasCurlyBraces = true; 1427 } 1428 1429 // If we have ${:foo}, then this is not a real operand reference, it is a 1430 // "magic" string reference, just like in .td files. Arrange to call 1431 // PrintSpecial. 1432 if (HasCurlyBraces && *LastEmitted == ':') { 1433 ++LastEmitted; 1434 const char *StrStart = LastEmitted; 1435 const char *StrEnd = strchr(StrStart, '}'); 1436 if (StrEnd == 0) { 1437 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 1438 + std::string(AsmStr) + "'"); 1439 } 1440 1441 std::string Val(StrStart, StrEnd); 1442 PrintSpecial(MI, Val.c_str()); 1443 LastEmitted = StrEnd+1; 1444 break; 1445 } 1446 1447 const char *IDStart = LastEmitted; 1448 char *IDEnd; 1449 errno = 0; 1450 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs. 1451 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) { 1452 llvm_report_error("Bad $ operand number in inline asm string: '" 1453 + std::string(AsmStr) + "'"); 1454 } 1455 LastEmitted = IDEnd; 1456 1457 char Modifier[2] = { 0, 0 }; 1458 1459 if (HasCurlyBraces) { 1460 // If we have curly braces, check for a modifier character. This 1461 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm. 1462 if (*LastEmitted == ':') { 1463 ++LastEmitted; // Consume ':' character. 1464 if (*LastEmitted == 0) { 1465 llvm_report_error("Bad ${:} expression in inline asm string: '" 1466 + std::string(AsmStr) + "'"); 1467 } 1468 1469 Modifier[0] = *LastEmitted; 1470 ++LastEmitted; // Consume modifier character. 1471 } 1472 1473 if (*LastEmitted != '}') { 1474 llvm_report_error("Bad ${} expression in inline asm string: '" 1475 + std::string(AsmStr) + "'"); 1476 } 1477 ++LastEmitted; // Consume '}' character. 1478 } 1479 1480 if ((unsigned)Val >= NumOperands-1) { 1481 llvm_report_error("Invalid $ operand number in inline asm string: '" 1482 + std::string(AsmStr) + "'"); 1483 } 1484 1485 // Okay, we finally have a value number. Ask the target to print this 1486 // operand! 1487 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) { 1488 unsigned OpNo = 1; 1489 1490 bool Error = false; 1491 1492 // Scan to find the machine operand number for the operand. 1493 for (; Val; --Val) { 1494 if (OpNo >= MI->getNumOperands()) break; 1495 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1496 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; 1497 } 1498 1499 if (OpNo >= MI->getNumOperands()) { 1500 Error = true; 1501 } else { 1502 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1503 ++OpNo; // Skip over the ID number. 1504 1505 if (Modifier[0]=='l') // labels are target independent 1506 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(), 1507 false, false, false); 1508 else { 1509 AsmPrinter *AP = const_cast<AsmPrinter*>(this); 1510 if ((OpFlags & 7) == 4) { 1511 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant, 1512 Modifier[0] ? Modifier : 0); 1513 } else { 1514 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant, 1515 Modifier[0] ? Modifier : 0); 1516 } 1517 } 1518 } 1519 if (Error) { 1520 std::string msg; 1521 raw_string_ostream Msg(msg); 1522 Msg << "Invalid operand found in inline asm: '" 1523 << AsmStr << "'\n"; 1524 MI->print(Msg); 1525 llvm_report_error(Msg.str()); 1526 } 1527 } 1528 break; 1529 } 1530 } 1531 } 1532 O << "\n\t" << TAI->getInlineAsmEnd() << '\n'; 1533} 1534 1535/// printImplicitDef - This method prints the specified machine instruction 1536/// that is an implicit def. 1537void AsmPrinter::printImplicitDef(const MachineInstr *MI) const { 1538 if (VerboseAsm) 1539 O << '\t' << TAI->getCommentString() << " implicit-def: " 1540 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n'; 1541} 1542 1543/// printLabel - This method prints a local label used by debug and 1544/// exception handling tables. 1545void AsmPrinter::printLabel(const MachineInstr *MI) const { 1546 printLabel(MI->getOperand(0).getImm()); 1547} 1548 1549void AsmPrinter::printLabel(unsigned Id) const { 1550 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n"; 1551} 1552 1553/// printDeclare - This method prints a local variable declaration used by 1554/// debug tables. 1555/// FIXME: It doesn't really print anything rather it inserts a DebugVariable 1556/// entry into dwarf table. 1557void AsmPrinter::printDeclare(const MachineInstr *MI) const { 1558 unsigned FI = MI->getOperand(0).getIndex(); 1559 GlobalValue *GV = MI->getOperand(1).getGlobal(); 1560 DW->RecordVariable(cast<GlobalVariable>(GV), FI, MI); 1561} 1562 1563/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM 1564/// instruction, using the specified assembler variant. Targets should 1565/// overried this to format as appropriate. 1566bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1567 unsigned AsmVariant, const char *ExtraCode) { 1568 // Target doesn't support this yet! 1569 return true; 1570} 1571 1572bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 1573 unsigned AsmVariant, 1574 const char *ExtraCode) { 1575 // Target doesn't support this yet! 1576 return true; 1577} 1578 1579/// printBasicBlockLabel - This method prints the label for the specified 1580/// MachineBasicBlock 1581void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB, 1582 bool printAlign, 1583 bool printColon, 1584 bool printComment) const { 1585 if (printAlign) { 1586 unsigned Align = MBB->getAlignment(); 1587 if (Align) 1588 EmitAlignment(Log2_32(Align)); 1589 } 1590 1591 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_' 1592 << MBB->getNumber(); 1593 if (printColon) 1594 O << ':'; 1595 if (printComment && MBB->getBasicBlock()) 1596 O << '\t' << TAI->getCommentString() << ' ' 1597 << MBB->getBasicBlock()->getNameStr(); 1598} 1599 1600/// printPICJumpTableSetLabel - This method prints a set label for the 1601/// specified MachineBasicBlock for a jumptable entry. 1602void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 1603 const MachineBasicBlock *MBB) const { 1604 if (!TAI->getSetDirective()) 1605 return; 1606 1607 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix() 1608 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','; 1609 printBasicBlockLabel(MBB, false, false, false); 1610 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 1611 << '_' << uid << '\n'; 1612} 1613 1614void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2, 1615 const MachineBasicBlock *MBB) const { 1616 if (!TAI->getSetDirective()) 1617 return; 1618 1619 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix() 1620 << getFunctionNumber() << '_' << uid << '_' << uid2 1621 << "_set_" << MBB->getNumber() << ','; 1622 printBasicBlockLabel(MBB, false, false, false); 1623 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 1624 << '_' << uid << '_' << uid2 << '\n'; 1625} 1626 1627/// printDataDirective - This method prints the asm directive for the 1628/// specified type. 1629void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) { 1630 const TargetData *TD = TM.getTargetData(); 1631 switch (type->getTypeID()) { 1632 case Type::FloatTyID: case Type::DoubleTyID: 1633 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID: 1634 assert(0 && "Should have already output floating point constant."); 1635 default: 1636 assert(0 && "Can't handle printing this type of thing"); 1637 case Type::IntegerTyID: { 1638 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth(); 1639 if (BitWidth <= 8) 1640 O << TAI->getData8bitsDirective(AddrSpace); 1641 else if (BitWidth <= 16) 1642 O << TAI->getData16bitsDirective(AddrSpace); 1643 else if (BitWidth <= 32) 1644 O << TAI->getData32bitsDirective(AddrSpace); 1645 else if (BitWidth <= 64) { 1646 assert(TAI->getData64bitsDirective(AddrSpace) && 1647 "Target cannot handle 64-bit constant exprs!"); 1648 O << TAI->getData64bitsDirective(AddrSpace); 1649 } else { 1650 llvm_unreachable("Target cannot handle given data directive width!"); 1651 } 1652 break; 1653 } 1654 case Type::PointerTyID: 1655 if (TD->getPointerSize() == 8) { 1656 assert(TAI->getData64bitsDirective(AddrSpace) && 1657 "Target cannot handle 64-bit pointer exprs!"); 1658 O << TAI->getData64bitsDirective(AddrSpace); 1659 } else if (TD->getPointerSize() == 2) { 1660 O << TAI->getData16bitsDirective(AddrSpace); 1661 } else if (TD->getPointerSize() == 1) { 1662 O << TAI->getData8bitsDirective(AddrSpace); 1663 } else { 1664 O << TAI->getData32bitsDirective(AddrSpace); 1665 } 1666 break; 1667 } 1668} 1669 1670void AsmPrinter::printVisibility(const std::string& Name, 1671 unsigned Visibility) const { 1672 if (Visibility == GlobalValue::HiddenVisibility) { 1673 if (const char *Directive = TAI->getHiddenDirective()) 1674 O << Directive << Name << '\n'; 1675 } else if (Visibility == GlobalValue::ProtectedVisibility) { 1676 if (const char *Directive = TAI->getProtectedDirective()) 1677 O << Directive << Name << '\n'; 1678 } 1679} 1680 1681void AsmPrinter::printOffset(int64_t Offset) const { 1682 if (Offset > 0) 1683 O << '+' << Offset; 1684 else if (Offset < 0) 1685 O << Offset; 1686} 1687 1688GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) { 1689 if (!S->usesMetadata()) 1690 return 0; 1691 1692 gcp_iterator GCPI = GCMetadataPrinters.find(S); 1693 if (GCPI != GCMetadataPrinters.end()) 1694 return GCPI->second; 1695 1696 const char *Name = S->getName().c_str(); 1697 1698 for (GCMetadataPrinterRegistry::iterator 1699 I = GCMetadataPrinterRegistry::begin(), 1700 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 1701 if (strcmp(Name, I->getName()) == 0) { 1702 GCMetadataPrinter *GMP = I->instantiate(); 1703 GMP->S = S; 1704 GCMetadataPrinters.insert(std::make_pair(S, GMP)); 1705 return GMP; 1706 } 1707 1708 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n"; 1709 llvm_unreachable(0); 1710} 1711 1712/// EmitComments - Pretty-print comments for instructions 1713void AsmPrinter::EmitComments(const MachineInstr &MI) const 1714{ 1715 if (VerboseAsm) { 1716 if (!MI.getDebugLoc().isUnknown()) { 1717 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc()); 1718 1719 // Print source line info 1720 O.PadToColumn(TAI->getCommentColumn(), 1); 1721 O << TAI->getCommentString() << " SrcLine "; 1722 if (DLT.CompileUnit->hasInitializer()) { 1723 Constant *Name = DLT.CompileUnit->getInitializer(); 1724 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name)) 1725 if (NameString->isString()) { 1726 O << NameString->getAsString() << " "; 1727 } 1728 } 1729 O << DLT.Line; 1730 if (DLT.Col != 0) 1731 O << ":" << DLT.Col; 1732 } 1733 } 1734} 1735 1736/// EmitComments - Pretty-print comments for instructions 1737void AsmPrinter::EmitComments(const MCInst &MI) const 1738{ 1739 if (VerboseAsm) { 1740 if (!MI.getDebugLoc().isUnknown()) { 1741 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc()); 1742 1743 // Print source line info 1744 O.PadToColumn(TAI->getCommentColumn(), 1); 1745 O << TAI->getCommentString() << " SrcLine "; 1746 if (DLT.CompileUnit->hasInitializer()) { 1747 Constant *Name = DLT.CompileUnit->getInitializer(); 1748 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name)) 1749 if (NameString->isString()) { 1750 O << NameString->getAsString() << " "; 1751 } 1752 } 1753 O << DLT.Line; 1754 if (DLT.Col != 0) 1755 O << ":" << DLT.Col; 1756 } 1757 } 1758} 1759