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