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