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 #define DEBUG_TYPE "asm-printer" 15 #include "llvm/CodeGen/AsmPrinter.h" 16 #include "DwarfDebug.h" 17 #include "DwarfException.h" 18 #include "llvm/Module.h" 19 #include "llvm/CodeGen/GCMetadataPrinter.h" 20 #include "llvm/CodeGen/MachineConstantPool.h" 21 #include "llvm/CodeGen/MachineFrameInfo.h" 22 #include "llvm/CodeGen/MachineFunction.h" 23 #include "llvm/CodeGen/MachineJumpTableInfo.h" 24 #include "llvm/CodeGen/MachineLoopInfo.h" 25 #include "llvm/CodeGen/MachineModuleInfo.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/DebugInfo.h" 28 #include "llvm/MC/MCAsmInfo.h" 29 #include "llvm/MC/MCContext.h" 30 #include "llvm/MC/MCExpr.h" 31 #include "llvm/MC/MCInst.h" 32 #include "llvm/MC/MCSection.h" 33 #include "llvm/MC/MCStreamer.h" 34 #include "llvm/MC/MCSymbol.h" 35 #include "llvm/Target/Mangler.h" 36 #include "llvm/Target/TargetData.h" 37 #include "llvm/Target/TargetInstrInfo.h" 38 #include "llvm/Target/TargetLowering.h" 39 #include "llvm/Target/TargetLoweringObjectFile.h" 40 #include "llvm/Target/TargetRegisterInfo.h" 41 #include "llvm/ADT/SmallString.h" 42 #include "llvm/ADT/Statistic.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/Format.h" 45 #include "llvm/Support/Timer.h" 46 using namespace llvm; 47 48 static const char *DWARFGroupName = "DWARF Emission"; 49 static const char *DbgTimerName = "DWARF Debug Writer"; 50 static const char *EHTimerName = "DWARF Exception Writer"; 51 52 STATISTIC(EmittedInsts, "Number of machine instrs printed"); 53 54 char AsmPrinter::ID = 0; 55 56 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type; 57 static gcp_map_type &getGCMap(void *&P) { 58 if (P == 0) 59 P = new gcp_map_type(); 60 return *(gcp_map_type*)P; 61 } 62 63 64 /// getGVAlignmentLog2 - Return the alignment to use for the specified global 65 /// value in log2 form. This rounds up to the preferred alignment if possible 66 /// and legal. 67 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD, 68 unsigned InBits = 0) { 69 unsigned NumBits = 0; 70 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 71 NumBits = TD.getPreferredAlignmentLog(GVar); 72 73 // If InBits is specified, round it to it. 74 if (InBits > NumBits) 75 NumBits = InBits; 76 77 // If the GV has a specified alignment, take it into account. 78 if (GV->getAlignment() == 0) 79 return NumBits; 80 81 unsigned GVAlign = Log2_32(GV->getAlignment()); 82 83 // If the GVAlign is larger than NumBits, or if we are required to obey 84 // NumBits because the GV has an assigned section, obey it. 85 if (GVAlign > NumBits || GV->hasSection()) 86 NumBits = GVAlign; 87 return NumBits; 88 } 89 90 91 92 93 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer) 94 : MachineFunctionPass(&ID), 95 TM(tm), MAI(tm.getMCAsmInfo()), 96 OutContext(Streamer.getContext()), 97 OutStreamer(Streamer), 98 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) { 99 DD = 0; DE = 0; MMI = 0; LI = 0; 100 GCMetadataPrinters = 0; 101 VerboseAsm = Streamer.isVerboseAsm(); 102 } 103 104 AsmPrinter::~AsmPrinter() { 105 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized"); 106 107 if (GCMetadataPrinters != 0) { 108 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 109 110 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I) 111 delete I->second; 112 delete &GCMap; 113 GCMetadataPrinters = 0; 114 } 115 116 delete &OutStreamer; 117 } 118 119 /// getFunctionNumber - Return a unique ID for the current function. 120 /// 121 unsigned AsmPrinter::getFunctionNumber() const { 122 return MF->getFunctionNumber(); 123 } 124 125 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 126 return TM.getTargetLowering()->getObjFileLowering(); 127 } 128 129 130 /// getTargetData - Return information about data layout. 131 const TargetData &AsmPrinter::getTargetData() const { 132 return *TM.getTargetData(); 133 } 134 135 /// getCurrentSection() - Return the current section we are emitting to. 136 const MCSection *AsmPrinter::getCurrentSection() const { 137 return OutStreamer.getCurrentSection(); 138 } 139 140 141 142 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 143 AU.setPreservesAll(); 144 MachineFunctionPass::getAnalysisUsage(AU); 145 AU.addRequired<MachineModuleInfo>(); 146 AU.addRequired<GCModuleInfo>(); 147 if (isVerbose()) 148 AU.addRequired<MachineLoopInfo>(); 149 } 150 151 bool AsmPrinter::doInitialization(Module &M) { 152 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 153 MMI->AnalyzeModule(M); 154 155 // Initialize TargetLoweringObjectFile. 156 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 157 .Initialize(OutContext, TM); 158 159 Mang = new Mangler(OutContext, *TM.getTargetData()); 160 161 // Allow the target to emit any magic that it wants at the start of the file. 162 EmitStartOfAsmFile(M); 163 164 // Very minimal debug info. It is ignored if we emit actual debug info. If we 165 // don't, this at least helps the user find where a global came from. 166 if (MAI->hasSingleParameterDotFile()) { 167 // .file "foo.c" 168 OutStreamer.EmitFileDirective(M.getModuleIdentifier()); 169 } 170 171 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 172 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 173 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I) 174 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 175 MP->beginAssembly(*this); 176 177 // Emit module-level inline asm if it exists. 178 if (!M.getModuleInlineAsm().empty()) { 179 OutStreamer.AddComment("Start of file scope inline assembly"); 180 OutStreamer.AddBlankLine(); 181 EmitInlineAsm(M.getModuleInlineAsm(), 0/*no loc cookie*/); 182 OutStreamer.AddComment("End of file scope inline assembly"); 183 OutStreamer.AddBlankLine(); 184 } 185 186 if (MAI->doesSupportDebugInformation()) 187 DD = new DwarfDebug(this, &M); 188 189 if (MAI->doesSupportExceptionHandling()) 190 DE = new DwarfException(this); 191 192 return false; 193 } 194 195 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const { 196 switch ((GlobalValue::LinkageTypes)Linkage) { 197 case GlobalValue::CommonLinkage: 198 case GlobalValue::LinkOnceAnyLinkage: 199 case GlobalValue::LinkOnceODRLinkage: 200 case GlobalValue::WeakAnyLinkage: 201 case GlobalValue::WeakODRLinkage: 202 case GlobalValue::LinkerPrivateLinkage: 203 if (MAI->getWeakDefDirective() != 0) { 204 // .globl _foo 205 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global); 206 // .weak_definition _foo 207 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition); 208 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) { 209 // .globl _foo 210 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global); 211 // FIXME: linkonce should be a section attribute, handled by COFF Section 212 // assignment. 213 // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce 214 // .linkonce discard 215 // FIXME: It would be nice to use .linkonce samesize for non-common 216 // globals. 217 OutStreamer.EmitRawText(StringRef(LinkOnce)); 218 } else { 219 // .weak _foo 220 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak); 221 } 222 break; 223 case GlobalValue::DLLExportLinkage: 224 case GlobalValue::AppendingLinkage: 225 // FIXME: appending linkage variables should go into a section of 226 // their name or something. For now, just emit them as external. 227 case GlobalValue::ExternalLinkage: 228 // If external or appending, declare as a global symbol. 229 // .globl _foo 230 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global); 231 break; 232 case GlobalValue::PrivateLinkage: 233 case GlobalValue::InternalLinkage: 234 break; 235 default: 236 llvm_unreachable("Unknown linkage type!"); 237 } 238 } 239 240 241 /// EmitGlobalVariable - Emit the specified global variable to the .s file. 242 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 243 if (!GV->hasInitializer()) // External globals require no code. 244 return; 245 246 // Check to see if this is a special global used by LLVM, if so, emit it. 247 if (EmitSpecialLLVMGlobal(GV)) 248 return; 249 250 MCSymbol *GVSym = Mang->getSymbol(GV); 251 EmitVisibility(GVSym, GV->getVisibility()); 252 253 if (MAI->hasDotTypeDotSizeDirective()) 254 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject); 255 256 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 257 258 const TargetData *TD = TM.getTargetData(); 259 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType()); 260 261 // If the alignment is specified, we *must* obey it. Overaligning a global 262 // with a specified alignment is a prompt way to break globals emitted to 263 // sections and expected to be contiguous (e.g. ObjC metadata). 264 unsigned AlignLog = getGVAlignmentLog2(GV, *TD); 265 266 // Handle common and BSS local symbols (.lcomm). 267 if (GVKind.isCommon() || GVKind.isBSSLocal()) { 268 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 269 270 if (isVerbose()) { 271 WriteAsOperand(OutStreamer.GetCommentOS(), GV, 272 /*PrintType=*/false, GV->getParent()); 273 OutStreamer.GetCommentOS() << '\n'; 274 } 275 276 // Handle common symbols. 277 if (GVKind.isCommon()) { 278 // .comm _foo, 42, 4 279 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog); 280 return; 281 } 282 283 // Handle local BSS symbols. 284 if (MAI->hasMachoZeroFillDirective()) { 285 const MCSection *TheSection = 286 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM); 287 // .zerofill __DATA, __bss, _foo, 400, 5 288 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog); 289 return; 290 } 291 292 if (MAI->hasLCOMMDirective()) { 293 // .lcomm _foo, 42 294 OutStreamer.EmitLocalCommonSymbol(GVSym, Size); 295 return; 296 } 297 298 // .local _foo 299 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local); 300 // .comm _foo, 42, 4 301 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog); 302 return; 303 } 304 305 const MCSection *TheSection = 306 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM); 307 308 // Handle the zerofill directive on darwin, which is a special form of BSS 309 // emission. 310 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) { 311 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined. 312 313 // .globl _foo 314 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global); 315 // .zerofill __DATA, __common, _foo, 400, 5 316 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog); 317 return; 318 } 319 320 OutStreamer.SwitchSection(TheSection); 321 322 EmitLinkage(GV->getLinkage(), GVSym); 323 EmitAlignment(AlignLog, GV); 324 325 if (isVerbose()) { 326 WriteAsOperand(OutStreamer.GetCommentOS(), GV, 327 /*PrintType=*/false, GV->getParent()); 328 OutStreamer.GetCommentOS() << '\n'; 329 } 330 OutStreamer.EmitLabel(GVSym); 331 332 EmitGlobalConstant(GV->getInitializer()); 333 334 if (MAI->hasDotTypeDotSizeDirective()) 335 // .size foo, 42 336 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext)); 337 338 OutStreamer.AddBlankLine(); 339 } 340 341 /// EmitFunctionHeader - This method emits the header for the current 342 /// function. 343 void AsmPrinter::EmitFunctionHeader() { 344 // Print out constants referenced by the function 345 EmitConstantPool(); 346 347 // Print the 'header' of function. 348 const Function *F = MF->getFunction(); 349 350 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM)); 351 EmitVisibility(CurrentFnSym, F->getVisibility()); 352 353 EmitLinkage(F->getLinkage(), CurrentFnSym); 354 EmitAlignment(MF->getAlignment(), F); 355 356 if (MAI->hasDotTypeDotSizeDirective()) 357 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction); 358 359 if (isVerbose()) { 360 WriteAsOperand(OutStreamer.GetCommentOS(), F, 361 /*PrintType=*/false, F->getParent()); 362 OutStreamer.GetCommentOS() << '\n'; 363 } 364 365 // Emit the CurrentFnSym. This is a virtual function to allow targets to 366 // do their wild and crazy things as required. 367 EmitFunctionEntryLabel(); 368 369 // If the function had address-taken blocks that got deleted, then we have 370 // references to the dangling symbols. Emit them at the start of the function 371 // so that we don't get references to undefined symbols. 372 std::vector<MCSymbol*> DeadBlockSyms; 373 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms); 374 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) { 375 OutStreamer.AddComment("Address taken block that was later removed"); 376 OutStreamer.EmitLabel(DeadBlockSyms[i]); 377 } 378 379 // Add some workaround for linkonce linkage on Cygwin\MinGW. 380 if (MAI->getLinkOnceDirective() != 0 && 381 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) { 382 // FIXME: What is this? 383 MCSymbol *FakeStub = 384 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+ 385 CurrentFnSym->getName()); 386 OutStreamer.EmitLabel(FakeStub); 387 } 388 389 // Emit pre-function debug and/or EH information. 390 if (DE) { 391 if (TimePassesIsEnabled) { 392 NamedRegionTimer T(EHTimerName, DWARFGroupName); 393 DE->BeginFunction(MF); 394 } else { 395 DE->BeginFunction(MF); 396 } 397 } 398 if (DD) { 399 if (TimePassesIsEnabled) { 400 NamedRegionTimer T(DbgTimerName, DWARFGroupName); 401 DD->beginFunction(MF); 402 } else { 403 DD->beginFunction(MF); 404 } 405 } 406 } 407 408 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the 409 /// function. This can be overridden by targets as required to do custom stuff. 410 void AsmPrinter::EmitFunctionEntryLabel() { 411 // The function label could have already been emitted if two symbols end up 412 // conflicting due to asm renaming. Detect this and emit an error. 413 if (CurrentFnSym->isUndefined()) 414 return OutStreamer.EmitLabel(CurrentFnSym); 415 416 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 417 "' label emitted multiple times to assembly file"); 418 } 419 420 421 /// EmitComments - Pretty-print comments for instructions. 422 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) { 423 const MachineFunction *MF = MI.getParent()->getParent(); 424 const TargetMachine &TM = MF->getTarget(); 425 426 DebugLoc DL = MI.getDebugLoc(); 427 if (!DL.isUnknown()) { // Print source line info. 428 DIScope Scope(DL.getScope(MF->getFunction()->getContext())); 429 // Omit the directory, because it's likely to be long and uninteresting. 430 if (Scope.Verify()) 431 CommentOS << Scope.getFilename(); 432 else 433 CommentOS << "<unknown>"; 434 CommentOS << ':' << DL.getLine(); 435 if (DL.getCol() != 0) 436 CommentOS << ':' << DL.getCol(); 437 CommentOS << '\n'; 438 } 439 440 // Check for spills and reloads 441 int FI; 442 443 const MachineFrameInfo *FrameInfo = MF->getFrameInfo(); 444 445 // We assume a single instruction only has a spill or reload, not 446 // both. 447 const MachineMemOperand *MMO; 448 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) { 449 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 450 MMO = *MI.memoperands_begin(); 451 CommentOS << MMO->getSize() << "-byte Reload\n"; 452 } 453 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) { 454 if (FrameInfo->isSpillSlotObjectIndex(FI)) 455 CommentOS << MMO->getSize() << "-byte Folded Reload\n"; 456 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) { 457 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 458 MMO = *MI.memoperands_begin(); 459 CommentOS << MMO->getSize() << "-byte Spill\n"; 460 } 461 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) { 462 if (FrameInfo->isSpillSlotObjectIndex(FI)) 463 CommentOS << MMO->getSize() << "-byte Folded Spill\n"; 464 } 465 466 // Check for spill-induced copies 467 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 468 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg, 469 SrcSubIdx, DstSubIdx)) { 470 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) 471 CommentOS << " Reload Reuse\n"; 472 } 473 } 474 475 /// EmitImplicitDef - This method emits the specified machine instruction 476 /// that is an implicit def. 477 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) { 478 unsigned RegNo = MI->getOperand(0).getReg(); 479 AP.OutStreamer.AddComment(Twine("implicit-def: ") + 480 AP.TM.getRegisterInfo()->getName(RegNo)); 481 AP.OutStreamer.AddBlankLine(); 482 } 483 484 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) { 485 std::string Str = "kill:"; 486 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 487 const MachineOperand &Op = MI->getOperand(i); 488 assert(Op.isReg() && "KILL instruction must have only register operands"); 489 Str += ' '; 490 Str += AP.TM.getRegisterInfo()->getName(Op.getReg()); 491 Str += (Op.isDef() ? "<def>" : "<kill>"); 492 } 493 AP.OutStreamer.AddComment(Str); 494 AP.OutStreamer.AddBlankLine(); 495 } 496 497 /// EmitDebugValueComment - This method handles the target-independent form 498 /// of DBG_VALUE, returning true if it was able to do so. A false return 499 /// means the target will need to handle MI in EmitInstruction. 500 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) { 501 // This code handles only the 3-operand target-independent form. 502 if (MI->getNumOperands() != 3) 503 return false; 504 505 SmallString<128> Str; 506 raw_svector_ostream OS(Str); 507 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: "; 508 509 // cast away const; DIetc do not take const operands for some reason. 510 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata())); 511 if (V.getContext().isSubprogram()) 512 OS << DISubprogram(V.getContext().getNode()).getDisplayName() << ":"; 513 OS << V.getName() << " <- "; 514 515 // Register or immediate value. Register 0 means undef. 516 if (MI->getOperand(0).isFPImm()) { 517 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF()); 518 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) { 519 OS << (double)APF.convertToFloat(); 520 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) { 521 OS << APF.convertToDouble(); 522 } else { 523 // There is no good way to print long double. Convert a copy to 524 // double. Ah well, it's only a comment. 525 bool ignored; 526 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 527 &ignored); 528 OS << "(long double) " << APF.convertToDouble(); 529 } 530 } else if (MI->getOperand(0).isImm()) { 531 OS << MI->getOperand(0).getImm(); 532 } else { 533 assert(MI->getOperand(0).isReg() && "Unknown operand type"); 534 if (MI->getOperand(0).getReg() == 0) { 535 // Suppress offset, it is not meaningful here. 536 OS << "undef"; 537 // NOTE: Want this comment at start of line, don't emit with AddComment. 538 AP.OutStreamer.EmitRawText(OS.str()); 539 return true; 540 } 541 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg()); 542 } 543 544 OS << '+' << MI->getOperand(1).getImm(); 545 // NOTE: Want this comment at start of line, don't emit with AddComment. 546 AP.OutStreamer.EmitRawText(OS.str()); 547 return true; 548 } 549 550 /// EmitFunctionBody - This method emits the body and trailer for a 551 /// function. 552 void AsmPrinter::EmitFunctionBody() { 553 // Emit target-specific gunk before the function body. 554 EmitFunctionBodyStart(); 555 556 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo(); 557 558 // Print out code for the function. 559 bool HasAnyRealCode = false; 560 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); 561 I != E; ++I) { 562 // Print a label for the basic block. 563 EmitBasicBlockStart(I); 564 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 565 II != IE; ++II) { 566 // Print the assembly for the instruction. 567 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() && 568 !II->isDebugValue()) { 569 HasAnyRealCode = true; 570 ++EmittedInsts; 571 } 572 573 if (ShouldPrintDebugScopes) { 574 if (TimePassesIsEnabled) { 575 NamedRegionTimer T(DbgTimerName, DWARFGroupName); 576 DD->beginScope(II); 577 } else { 578 DD->beginScope(II); 579 } 580 } 581 582 if (isVerbose()) 583 EmitComments(*II, OutStreamer.GetCommentOS()); 584 585 switch (II->getOpcode()) { 586 case TargetOpcode::DBG_LABEL: 587 case TargetOpcode::EH_LABEL: 588 case TargetOpcode::GC_LABEL: 589 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol()); 590 break; 591 case TargetOpcode::INLINEASM: 592 EmitInlineAsm(II); 593 break; 594 case TargetOpcode::DBG_VALUE: 595 if (isVerbose()) { 596 if (!EmitDebugValueComment(II, *this)) 597 EmitInstruction(II); 598 } 599 break; 600 case TargetOpcode::IMPLICIT_DEF: 601 if (isVerbose()) EmitImplicitDef(II, *this); 602 break; 603 case TargetOpcode::KILL: 604 if (isVerbose()) EmitKill(II, *this); 605 break; 606 default: 607 EmitInstruction(II); 608 break; 609 } 610 611 if (ShouldPrintDebugScopes) { 612 if (TimePassesIsEnabled) { 613 NamedRegionTimer T(DbgTimerName, DWARFGroupName); 614 DD->endScope(II); 615 } else { 616 DD->endScope(II); 617 } 618 } 619 } 620 } 621 622 // If the function is empty and the object file uses .subsections_via_symbols, 623 // then we need to emit *something* to the function body to prevent the 624 // labels from collapsing together. Just emit a noop. 625 if (MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) { 626 MCInst Noop; 627 TM.getInstrInfo()->getNoopForMachoTarget(Noop); 628 if (Noop.getOpcode()) { 629 OutStreamer.AddComment("avoids zero-length function"); 630 OutStreamer.EmitInstruction(Noop); 631 } else // Target not mc-ized yet. 632 OutStreamer.EmitRawText(StringRef("\tnop\n")); 633 } 634 635 // Emit target-specific gunk after the function body. 636 EmitFunctionBodyEnd(); 637 638 // If the target wants a .size directive for the size of the function, emit 639 // it. 640 if (MAI->hasDotTypeDotSizeDirective()) { 641 // Create a symbol for the end of function, so we can get the size as 642 // difference between the function label and the temp label. 643 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol(); 644 OutStreamer.EmitLabel(FnEndLabel); 645 646 const MCExpr *SizeExp = 647 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext), 648 MCSymbolRefExpr::Create(CurrentFnSym, OutContext), 649 OutContext); 650 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp); 651 } 652 653 // Emit post-function debug information. 654 if (DD) { 655 if (TimePassesIsEnabled) { 656 NamedRegionTimer T(DbgTimerName, DWARFGroupName); 657 DD->endFunction(MF); 658 } else { 659 DD->endFunction(MF); 660 } 661 } 662 if (DE) { 663 if (TimePassesIsEnabled) { 664 NamedRegionTimer T(EHTimerName, DWARFGroupName); 665 DE->EndFunction(); 666 } else { 667 DE->EndFunction(); 668 } 669 } 670 MMI->EndFunction(); 671 672 // Print out jump tables referenced by the function. 673 EmitJumpTableInfo(); 674 675 OutStreamer.AddBlankLine(); 676 } 677 678 /// getDebugValueLocation - Get location information encoded by DBG_VALUE 679 /// operands. 680 MachineLocation AsmPrinter::getDebugValueLocation(const MachineInstr *MI) const { 681 // Target specific DBG_VALUE instructions are handled by each target. 682 return MachineLocation(); 683 } 684 685 bool AsmPrinter::doFinalization(Module &M) { 686 // Emit global variables. 687 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 688 I != E; ++I) 689 EmitGlobalVariable(I); 690 691 // Finalize debug and EH information. 692 if (DE) { 693 if (TimePassesIsEnabled) { 694 NamedRegionTimer T(EHTimerName, DWARFGroupName); 695 DE->EndModule(); 696 } else { 697 DE->EndModule(); 698 } 699 delete DE; DE = 0; 700 } 701 if (DD) { 702 if (TimePassesIsEnabled) { 703 NamedRegionTimer T(DbgTimerName, DWARFGroupName); 704 DD->endModule(); 705 } else { 706 DD->endModule(); 707 } 708 delete DD; DD = 0; 709 } 710 711 // If the target wants to know about weak references, print them all. 712 if (MAI->getWeakRefDirective()) { 713 // FIXME: This is not lazy, it would be nice to only print weak references 714 // to stuff that is actually used. Note that doing so would require targets 715 // to notice uses in operands (due to constant exprs etc). This should 716 // happen with the MC stuff eventually. 717 718 // Print out module-level global variables here. 719 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 720 I != E; ++I) { 721 if (!I->hasExternalWeakLinkage()) continue; 722 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference); 723 } 724 725 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 726 if (!I->hasExternalWeakLinkage()) continue; 727 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference); 728 } 729 } 730 731 if (MAI->hasSetDirective()) { 732 OutStreamer.AddBlankLine(); 733 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 734 I != E; ++I) { 735 MCSymbol *Name = Mang->getSymbol(I); 736 737 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal()); 738 MCSymbol *Target = Mang->getSymbol(GV); 739 740 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) 741 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global); 742 else if (I->hasWeakLinkage()) 743 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference); 744 else 745 assert(I->hasLocalLinkage() && "Invalid alias linkage"); 746 747 EmitVisibility(Name, I->getVisibility()); 748 749 // Emit the directives as assignments aka .set: 750 OutStreamer.EmitAssignment(Name, 751 MCSymbolRefExpr::Create(Target, OutContext)); 752 } 753 } 754 755 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 756 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 757 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 758 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I)) 759 MP->finishAssembly(*this); 760 761 // If we don't have any trampolines, then we don't require stack memory 762 // to be executable. Some targets have a directive to declare this. 763 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 764 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 765 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 766 OutStreamer.SwitchSection(S); 767 768 // Allow the target to emit any magic that it wants at the end of the file, 769 // after everything else has gone out. 770 EmitEndOfAsmFile(M); 771 772 delete Mang; Mang = 0; 773 MMI = 0; 774 775 OutStreamer.Finish(); 776 return false; 777 } 778 779 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 780 this->MF = &MF; 781 // Get the function symbol. 782 CurrentFnSym = Mang->getSymbol(MF.getFunction()); 783 784 if (isVerbose()) 785 LI = &getAnalysis<MachineLoopInfo>(); 786 } 787 788 namespace { 789 // SectionCPs - Keep track the alignment, constpool entries per Section. 790 struct SectionCPs { 791 const MCSection *S; 792 unsigned Alignment; 793 SmallVector<unsigned, 4> CPEs; 794 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {} 795 }; 796 } 797 798 /// EmitConstantPool - Print to the current output stream assembly 799 /// representations of the constants in the constant pool MCP. This is 800 /// used to print out constants which have been "spilled to memory" by 801 /// the code generator. 802 /// 803 void AsmPrinter::EmitConstantPool() { 804 const MachineConstantPool *MCP = MF->getConstantPool(); 805 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 806 if (CP.empty()) return; 807 808 // Calculate sections for constant pool entries. We collect entries to go into 809 // the same section together to reduce amount of section switch statements. 810 SmallVector<SectionCPs, 4> CPSections; 811 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 812 const MachineConstantPoolEntry &CPE = CP[i]; 813 unsigned Align = CPE.getAlignment(); 814 815 SectionKind Kind; 816 switch (CPE.getRelocationInfo()) { 817 default: llvm_unreachable("Unknown section kind"); 818 case 2: Kind = SectionKind::getReadOnlyWithRel(); break; 819 case 1: 820 Kind = SectionKind::getReadOnlyWithRelLocal(); 821 break; 822 case 0: 823 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) { 824 case 4: Kind = SectionKind::getMergeableConst4(); break; 825 case 8: Kind = SectionKind::getMergeableConst8(); break; 826 case 16: Kind = SectionKind::getMergeableConst16();break; 827 default: Kind = SectionKind::getMergeableConst(); break; 828 } 829 } 830 831 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind); 832 833 // The number of sections are small, just do a linear search from the 834 // last section to the first. 835 bool Found = false; 836 unsigned SecIdx = CPSections.size(); 837 while (SecIdx != 0) { 838 if (CPSections[--SecIdx].S == S) { 839 Found = true; 840 break; 841 } 842 } 843 if (!Found) { 844 SecIdx = CPSections.size(); 845 CPSections.push_back(SectionCPs(S, Align)); 846 } 847 848 if (Align > CPSections[SecIdx].Alignment) 849 CPSections[SecIdx].Alignment = Align; 850 CPSections[SecIdx].CPEs.push_back(i); 851 } 852 853 // Now print stuff into the calculated sections. 854 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 855 OutStreamer.SwitchSection(CPSections[i].S); 856 EmitAlignment(Log2_32(CPSections[i].Alignment)); 857 858 unsigned Offset = 0; 859 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 860 unsigned CPI = CPSections[i].CPEs[j]; 861 MachineConstantPoolEntry CPE = CP[CPI]; 862 863 // Emit inter-object padding for alignment. 864 unsigned AlignMask = CPE.getAlignment() - 1; 865 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 866 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/); 867 868 const Type *Ty = CPE.getType(); 869 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty); 870 871 // Emit the label with a comment on it. 872 if (isVerbose()) { 873 OutStreamer.GetCommentOS() << "constant pool "; 874 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(), 875 MF->getFunction()->getParent()); 876 OutStreamer.GetCommentOS() << '\n'; 877 } 878 OutStreamer.EmitLabel(GetCPISymbol(CPI)); 879 880 if (CPE.isMachineConstantPoolEntry()) 881 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 882 else 883 EmitGlobalConstant(CPE.Val.ConstVal); 884 } 885 } 886 } 887 888 /// EmitJumpTableInfo - Print assembly representations of the jump tables used 889 /// by the current function to the current output stream. 890 /// 891 void AsmPrinter::EmitJumpTableInfo() { 892 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 893 if (MJTI == 0) return; 894 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 895 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 896 if (JT.empty()) return; 897 898 // Pick the directive to use to print the jump table entries, and switch to 899 // the appropriate section. 900 const Function *F = MF->getFunction(); 901 bool JTInDiffSection = false; 902 if (// In PIC mode, we need to emit the jump table to the same section as the 903 // function body itself, otherwise the label differences won't make sense. 904 // FIXME: Need a better predicate for this: what about custom entries? 905 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 || 906 // We should also do if the section name is NULL or function is declared 907 // in discardable section 908 // FIXME: this isn't the right predicate, should be based on the MCSection 909 // for the function. 910 F->isWeakForLinker()) { 911 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM)); 912 } else { 913 // Otherwise, drop it in the readonly section. 914 const MCSection *ReadOnlySection = 915 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly()); 916 OutStreamer.SwitchSection(ReadOnlySection); 917 JTInDiffSection = true; 918 } 919 920 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData()))); 921 922 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 923 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 924 925 // If this jump table was deleted, ignore it. 926 if (JTBBs.empty()) continue; 927 928 // For the EK_LabelDifference32 entry, if the target supports .set, emit a 929 // .set directive for each unique entry. This reduces the number of 930 // relocations the assembler will generate for the jump table. 931 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 932 MAI->hasSetDirective()) { 933 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 934 const TargetLowering *TLI = TM.getTargetLowering(); 935 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 936 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 937 const MachineBasicBlock *MBB = JTBBs[ii]; 938 if (!EmittedSets.insert(MBB)) continue; 939 940 // .set LJTSet, LBB32-base 941 const MCExpr *LHS = 942 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext); 943 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 944 MCBinaryExpr::CreateSub(LHS, Base, OutContext)); 945 } 946 } 947 948 // On some targets (e.g. Darwin) we want to emit two consequtive labels 949 // before each jump table. The first label is never referenced, but tells 950 // the assembler and linker the extents of the jump table object. The 951 // second label is actually referenced by the code. 952 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) 953 // FIXME: This doesn't have to have any specific name, just any randomly 954 // named and numbered 'l' label would work. Simplify GetJTISymbol. 955 OutStreamer.EmitLabel(GetJTISymbol(JTI, true)); 956 957 OutStreamer.EmitLabel(GetJTISymbol(JTI)); 958 959 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 960 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI); 961 } 962 } 963 964 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 965 /// current stream. 966 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, 967 const MachineBasicBlock *MBB, 968 unsigned UID) const { 969 const MCExpr *Value = 0; 970 switch (MJTI->getEntryKind()) { 971 case MachineJumpTableInfo::EK_Inline: 972 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break; 973 case MachineJumpTableInfo::EK_Custom32: 974 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID, 975 OutContext); 976 break; 977 case MachineJumpTableInfo::EK_BlockAddress: 978 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 979 // .word LBB123 980 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext); 981 break; 982 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 983 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 984 // with a relocation as gp-relative, e.g.: 985 // .gprel32 LBB123 986 MCSymbol *MBBSym = MBB->getSymbol(); 987 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext)); 988 return; 989 } 990 991 case MachineJumpTableInfo::EK_LabelDifference32: { 992 // EK_LabelDifference32 - Each entry is the address of the block minus 993 // the address of the jump table. This is used for PIC jump tables where 994 // gprel32 is not supported. e.g.: 995 // .word LBB123 - LJTI1_2 996 // If the .set directive is supported, this is emitted as: 997 // .set L4_5_set_123, LBB123 - LJTI1_2 998 // .word L4_5_set_123 999 1000 // If we have emitted set directives for the jump table entries, print 1001 // them rather than the entries themselves. If we're emitting PIC, then 1002 // emit the table entries as differences between two text section labels. 1003 if (MAI->hasSetDirective()) { 1004 // If we used .set, reference the .set's symbol. 1005 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()), 1006 OutContext); 1007 break; 1008 } 1009 // Otherwise, use the difference as the jump table entry. 1010 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext); 1011 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext); 1012 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext); 1013 break; 1014 } 1015 } 1016 1017 assert(Value && "Unknown entry kind!"); 1018 1019 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData()); 1020 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0); 1021 } 1022 1023 1024 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 1025 /// special global used by LLVM. If so, emit it and return true, otherwise 1026 /// do nothing and return false. 1027 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 1028 if (GV->getName() == "llvm.used") { 1029 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 1030 EmitLLVMUsedList(GV->getInitializer()); 1031 return true; 1032 } 1033 1034 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 1035 if (GV->getSection() == "llvm.metadata" || 1036 GV->hasAvailableExternallyLinkage()) 1037 return true; 1038 1039 if (!GV->hasAppendingLinkage()) return false; 1040 1041 assert(GV->hasInitializer() && "Not a special LLVM global!"); 1042 1043 const TargetData *TD = TM.getTargetData(); 1044 unsigned Align = Log2_32(TD->getPointerPrefAlignment()); 1045 if (GV->getName() == "llvm.global_ctors") { 1046 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection()); 1047 EmitAlignment(Align); 1048 EmitXXStructorList(GV->getInitializer()); 1049 1050 if (TM.getRelocationModel() == Reloc::Static && 1051 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 1052 StringRef Sym(".constructors_used"); 1053 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym), 1054 MCSA_Reference); 1055 } 1056 return true; 1057 } 1058 1059 if (GV->getName() == "llvm.global_dtors") { 1060 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection()); 1061 EmitAlignment(Align); 1062 EmitXXStructorList(GV->getInitializer()); 1063 1064 if (TM.getRelocationModel() == Reloc::Static && 1065 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 1066 StringRef Sym(".destructors_used"); 1067 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym), 1068 MCSA_Reference); 1069 } 1070 return true; 1071 } 1072 1073 return false; 1074 } 1075 1076 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 1077 /// global in the specified llvm.used list for which emitUsedDirectiveFor 1078 /// is true, as being used with this directive. 1079 void AsmPrinter::EmitLLVMUsedList(Constant *List) { 1080 // Should be an array of 'i8*'. 1081 ConstantArray *InitList = dyn_cast<ConstantArray>(List); 1082 if (InitList == 0) return; 1083 1084 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 1085 const GlobalValue *GV = 1086 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 1087 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) 1088 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip); 1089 } 1090 } 1091 1092 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the 1093 /// function pointers, ignoring the init priority. 1094 void AsmPrinter::EmitXXStructorList(Constant *List) { 1095 // Should be an array of '{ int, void ()* }' structs. The first value is the 1096 // init priority, which we ignore. 1097 if (!isa<ConstantArray>(List)) return; 1098 ConstantArray *InitList = cast<ConstantArray>(List); 1099 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 1100 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){ 1101 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 1102 1103 if (CS->getOperand(1)->isNullValue()) 1104 return; // Found a null terminator, exit printing. 1105 // Emit the function pointer. 1106 EmitGlobalConstant(CS->getOperand(1)); 1107 } 1108 } 1109 1110 //===--------------------------------------------------------------------===// 1111 // Emission and print routines 1112 // 1113 1114 /// EmitInt8 - Emit a byte directive and value. 1115 /// 1116 void AsmPrinter::EmitInt8(int Value) const { 1117 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/); 1118 } 1119 1120 /// EmitInt16 - Emit a short directive and value. 1121 /// 1122 void AsmPrinter::EmitInt16(int Value) const { 1123 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/); 1124 } 1125 1126 /// EmitInt32 - Emit a long directive and value. 1127 /// 1128 void AsmPrinter::EmitInt32(int Value) const { 1129 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/); 1130 } 1131 1132 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size 1133 /// in bytes of the directive is specified by Size and Hi/Lo specify the 1134 /// labels. This implicitly uses .set if it is available. 1135 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 1136 unsigned Size) const { 1137 // Get the Hi-Lo expression. 1138 const MCExpr *Diff = 1139 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext), 1140 MCSymbolRefExpr::Create(Lo, OutContext), 1141 OutContext); 1142 1143 if (!MAI->hasSetDirective()) { 1144 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/); 1145 return; 1146 } 1147 1148 // Otherwise, emit with .set (aka assignment). 1149 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++); 1150 OutStreamer.EmitAssignment(SetLabel, Diff); 1151 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/); 1152 } 1153 1154 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo" 1155 /// where the size in bytes of the directive is specified by Size and Hi/Lo 1156 /// specify the labels. This implicitly uses .set if it is available. 1157 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset, 1158 const MCSymbol *Lo, unsigned Size) 1159 const { 1160 1161 // Emit Hi+Offset - Lo 1162 // Get the Hi+Offset expression. 1163 const MCExpr *Plus = 1164 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext), 1165 MCConstantExpr::Create(Offset, OutContext), 1166 OutContext); 1167 1168 // Get the Hi+Offset-Lo expression. 1169 const MCExpr *Diff = 1170 MCBinaryExpr::CreateSub(Plus, 1171 MCSymbolRefExpr::Create(Lo, OutContext), 1172 OutContext); 1173 1174 if (!MAI->hasSetDirective()) 1175 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/); 1176 else { 1177 // Otherwise, emit with .set (aka assignment). 1178 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++); 1179 OutStreamer.EmitAssignment(SetLabel, Diff); 1180 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/); 1181 } 1182 } 1183 1184 1185 //===----------------------------------------------------------------------===// 1186 1187 // EmitAlignment - Emit an alignment directive to the specified power of 1188 // two boundary. For example, if you pass in 3 here, you will get an 8 1189 // byte alignment. If a global value is specified, and if that global has 1190 // an explicit alignment requested, it will override the alignment request 1191 // if required for correctness. 1192 // 1193 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const { 1194 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits); 1195 1196 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment. 1197 1198 if (getCurrentSection()->getKind().isText()) 1199 OutStreamer.EmitCodeAlignment(1 << NumBits); 1200 else 1201 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0); 1202 } 1203 1204 //===----------------------------------------------------------------------===// 1205 // Constant emission. 1206 //===----------------------------------------------------------------------===// 1207 1208 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr. 1209 /// 1210 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) { 1211 MCContext &Ctx = AP.OutContext; 1212 1213 if (CV->isNullValue() || isa<UndefValue>(CV)) 1214 return MCConstantExpr::Create(0, Ctx); 1215 1216 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 1217 return MCConstantExpr::Create(CI->getZExtValue(), Ctx); 1218 1219 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 1220 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx); 1221 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 1222 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx); 1223 1224 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 1225 if (CE == 0) { 1226 llvm_unreachable("Unknown constant value to lower!"); 1227 return MCConstantExpr::Create(0, Ctx); 1228 } 1229 1230 switch (CE->getOpcode()) { 1231 default: 1232 // If the code isn't optimized, there may be outstanding folding 1233 // opportunities. Attempt to fold the expression using TargetData as a 1234 // last resort before giving up. 1235 if (Constant *C = 1236 ConstantFoldConstantExpression(CE, AP.TM.getTargetData())) 1237 if (C != CE) 1238 return LowerConstant(C, AP); 1239 #ifndef NDEBUG 1240 CE->dump(); 1241 #endif 1242 llvm_unreachable("FIXME: Don't support this constant expr"); 1243 case Instruction::GetElementPtr: { 1244 const TargetData &TD = *AP.TM.getTargetData(); 1245 // Generate a symbolic expression for the byte address 1246 const Constant *PtrVal = CE->getOperand(0); 1247 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end()); 1248 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0], 1249 IdxVec.size()); 1250 1251 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP); 1252 if (Offset == 0) 1253 return Base; 1254 1255 // Truncate/sext the offset to the pointer size. 1256 if (TD.getPointerSizeInBits() != 64) { 1257 int SExtAmount = 64-TD.getPointerSizeInBits(); 1258 Offset = (Offset << SExtAmount) >> SExtAmount; 1259 } 1260 1261 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx), 1262 Ctx); 1263 } 1264 1265 case Instruction::Trunc: 1266 // We emit the value and depend on the assembler to truncate the generated 1267 // expression properly. This is important for differences between 1268 // blockaddress labels. Since the two labels are in the same function, it 1269 // is reasonable to treat their delta as a 32-bit value. 1270 // FALL THROUGH. 1271 case Instruction::BitCast: 1272 return LowerConstant(CE->getOperand(0), AP); 1273 1274 case Instruction::IntToPtr: { 1275 const TargetData &TD = *AP.TM.getTargetData(); 1276 // Handle casts to pointers by changing them into casts to the appropriate 1277 // integer type. This promotes constant folding and simplifies this code. 1278 Constant *Op = CE->getOperand(0); 1279 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()), 1280 false/*ZExt*/); 1281 return LowerConstant(Op, AP); 1282 } 1283 1284 case Instruction::PtrToInt: { 1285 const TargetData &TD = *AP.TM.getTargetData(); 1286 // Support only foldable casts to/from pointers that can be eliminated by 1287 // changing the pointer to the appropriately sized integer type. 1288 Constant *Op = CE->getOperand(0); 1289 const Type *Ty = CE->getType(); 1290 1291 const MCExpr *OpExpr = LowerConstant(Op, AP); 1292 1293 // We can emit the pointer value into this slot if the slot is an 1294 // integer slot equal to the size of the pointer. 1295 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType())) 1296 return OpExpr; 1297 1298 // Otherwise the pointer is smaller than the resultant integer, mask off 1299 // the high bits so we are sure to get a proper truncation if the input is 1300 // a constant expr. 1301 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType()); 1302 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx); 1303 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx); 1304 } 1305 1306 // The MC library also has a right-shift operator, but it isn't consistently 1307 // signed or unsigned between different targets. 1308 case Instruction::Add: 1309 case Instruction::Sub: 1310 case Instruction::Mul: 1311 case Instruction::SDiv: 1312 case Instruction::SRem: 1313 case Instruction::Shl: 1314 case Instruction::And: 1315 case Instruction::Or: 1316 case Instruction::Xor: { 1317 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP); 1318 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP); 1319 switch (CE->getOpcode()) { 1320 default: llvm_unreachable("Unknown binary operator constant cast expr"); 1321 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx); 1322 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx); 1323 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx); 1324 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx); 1325 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx); 1326 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx); 1327 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx); 1328 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx); 1329 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx); 1330 } 1331 } 1332 } 1333 } 1334 1335 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace, 1336 AsmPrinter &AP); 1337 1338 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace, 1339 AsmPrinter &AP) { 1340 if (AddrSpace != 0 || !CA->isString()) { 1341 // Not a string. Print the values in successive locations 1342 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) 1343 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP); 1344 return; 1345 } 1346 1347 // Otherwise, it can be emitted as .ascii. 1348 SmallVector<char, 128> TmpVec; 1349 TmpVec.reserve(CA->getNumOperands()); 1350 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) 1351 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue()); 1352 1353 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace); 1354 } 1355 1356 static void EmitGlobalConstantVector(const ConstantVector *CV, 1357 unsigned AddrSpace, AsmPrinter &AP) { 1358 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 1359 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP); 1360 } 1361 1362 static void EmitGlobalConstantStruct(const ConstantStruct *CS, 1363 unsigned AddrSpace, AsmPrinter &AP) { 1364 // Print the fields in successive locations. Pad to align if needed! 1365 const TargetData *TD = AP.TM.getTargetData(); 1366 unsigned Size = TD->getTypeAllocSize(CS->getType()); 1367 const StructLayout *Layout = TD->getStructLayout(CS->getType()); 1368 uint64_t SizeSoFar = 0; 1369 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 1370 const Constant *Field = CS->getOperand(i); 1371 1372 // Check if padding is needed and insert one or more 0s. 1373 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType()); 1374 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 1375 - Layout->getElementOffset(i)) - FieldSize; 1376 SizeSoFar += FieldSize + PadSize; 1377 1378 // Now print the actual field value. 1379 EmitGlobalConstantImpl(Field, AddrSpace, AP); 1380 1381 // Insert padding - this may include padding to increase the size of the 1382 // current field up to the ABI size (if the struct is not packed) as well 1383 // as padding to ensure that the next field starts at the right offset. 1384 AP.OutStreamer.EmitZeros(PadSize, AddrSpace); 1385 } 1386 assert(SizeSoFar == Layout->getSizeInBytes() && 1387 "Layout of constant struct may be incorrect!"); 1388 } 1389 1390 static void EmitGlobalConstantUnion(const ConstantUnion *CU, 1391 unsigned AddrSpace, AsmPrinter &AP) { 1392 const TargetData *TD = AP.TM.getTargetData(); 1393 unsigned Size = TD->getTypeAllocSize(CU->getType()); 1394 1395 const Constant *Contents = CU->getOperand(0); 1396 unsigned FilledSize = TD->getTypeAllocSize(Contents->getType()); 1397 1398 // Print the actually filled part 1399 EmitGlobalConstantImpl(Contents, AddrSpace, AP); 1400 1401 // And pad with enough zeroes 1402 AP.OutStreamer.EmitZeros(Size-FilledSize, AddrSpace); 1403 } 1404 1405 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace, 1406 AsmPrinter &AP) { 1407 // FP Constants are printed as integer constants to avoid losing 1408 // precision. 1409 if (CFP->getType()->isDoubleTy()) { 1410 if (AP.isVerbose()) { 1411 double Val = CFP->getValueAPF().convertToDouble(); 1412 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n'; 1413 } 1414 1415 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1416 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace); 1417 return; 1418 } 1419 1420 if (CFP->getType()->isFloatTy()) { 1421 if (AP.isVerbose()) { 1422 float Val = CFP->getValueAPF().convertToFloat(); 1423 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n'; 1424 } 1425 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1426 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace); 1427 return; 1428 } 1429 1430 if (CFP->getType()->isX86_FP80Ty()) { 1431 // all long double variants are printed as hex 1432 // API needed to prevent premature destruction 1433 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1434 const uint64_t *p = API.getRawData(); 1435 if (AP.isVerbose()) { 1436 // Convert to double so we can print the approximate val as a comment. 1437 APFloat DoubleVal = CFP->getValueAPF(); 1438 bool ignored; 1439 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 1440 &ignored); 1441 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= " 1442 << DoubleVal.convertToDouble() << '\n'; 1443 } 1444 1445 if (AP.TM.getTargetData()->isBigEndian()) { 1446 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace); 1447 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1448 } else { 1449 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1450 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace); 1451 } 1452 1453 // Emit the tail padding for the long double. 1454 const TargetData &TD = *AP.TM.getTargetData(); 1455 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) - 1456 TD.getTypeStoreSize(CFP->getType()), AddrSpace); 1457 return; 1458 } 1459 1460 assert(CFP->getType()->isPPC_FP128Ty() && 1461 "Floating point constant type not handled"); 1462 // All long double variants are printed as hex 1463 // API needed to prevent premature destruction. 1464 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1465 const uint64_t *p = API.getRawData(); 1466 if (AP.TM.getTargetData()->isBigEndian()) { 1467 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1468 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace); 1469 } else { 1470 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace); 1471 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1472 } 1473 } 1474 1475 static void EmitGlobalConstantLargeInt(const ConstantInt *CI, 1476 unsigned AddrSpace, AsmPrinter &AP) { 1477 const TargetData *TD = AP.TM.getTargetData(); 1478 unsigned BitWidth = CI->getBitWidth(); 1479 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits"); 1480 1481 // We don't expect assemblers to support integer data directives 1482 // for more than 64 bits, so we emit the data in at most 64-bit 1483 // quantities at a time. 1484 const uint64_t *RawData = CI->getValue().getRawData(); 1485 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 1486 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i]; 1487 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace); 1488 } 1489 } 1490 1491 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace, 1492 AsmPrinter &AP) { 1493 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) { 1494 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType()); 1495 return AP.OutStreamer.EmitZeros(Size, AddrSpace); 1496 } 1497 1498 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1499 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType()); 1500 switch (Size) { 1501 case 1: 1502 case 2: 1503 case 4: 1504 case 8: 1505 if (AP.isVerbose()) 1506 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue()); 1507 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace); 1508 return; 1509 default: 1510 EmitGlobalConstantLargeInt(CI, AddrSpace, AP); 1511 return; 1512 } 1513 } 1514 1515 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 1516 return EmitGlobalConstantArray(CVA, AddrSpace, AP); 1517 1518 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 1519 return EmitGlobalConstantStruct(CVS, AddrSpace, AP); 1520 1521 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 1522 return EmitGlobalConstantFP(CFP, AddrSpace, AP); 1523 1524 if (isa<ConstantPointerNull>(CV)) { 1525 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType()); 1526 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace); 1527 return; 1528 } 1529 1530 if (const ConstantUnion *CVU = dyn_cast<ConstantUnion>(CV)) 1531 return EmitGlobalConstantUnion(CVU, AddrSpace, AP); 1532 1533 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 1534 return EmitGlobalConstantVector(V, AddrSpace, AP); 1535 1536 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 1537 // thread the streamer with EmitValue. 1538 AP.OutStreamer.EmitValue(LowerConstant(CV, AP), 1539 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()), 1540 AddrSpace); 1541 } 1542 1543 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 1544 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) { 1545 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1546 if (Size) 1547 EmitGlobalConstantImpl(CV, AddrSpace, *this); 1548 else if (MAI->hasSubsectionsViaSymbols()) { 1549 // If the global has zero size, emit a single byte so that two labels don't 1550 // look like they are at the same location. 1551 OutStreamer.EmitIntValue(0, 1, AddrSpace); 1552 } 1553 } 1554 1555 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 1556 // Target doesn't support this yet! 1557 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 1558 } 1559 1560 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 1561 if (Offset > 0) 1562 OS << '+' << Offset; 1563 else if (Offset < 0) 1564 OS << Offset; 1565 } 1566 1567 //===----------------------------------------------------------------------===// 1568 // Symbol Lowering Routines. 1569 //===----------------------------------------------------------------------===// 1570 1571 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler 1572 /// temporary label with the specified stem and unique ID. 1573 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const { 1574 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + 1575 Name + Twine(ID)); 1576 } 1577 1578 /// GetTempSymbol - Return an assembler temporary label with the specified 1579 /// stem. 1580 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const { 1581 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+ 1582 Name); 1583 } 1584 1585 1586 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 1587 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 1588 } 1589 1590 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 1591 return MMI->getAddrLabelSymbol(BB); 1592 } 1593 1594 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 1595 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 1596 return OutContext.GetOrCreateSymbol 1597 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber()) 1598 + "_" + Twine(CPID)); 1599 } 1600 1601 /// GetJTISymbol - Return the symbol for the specified jump table entry. 1602 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 1603 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 1604 } 1605 1606 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 1607 /// FIXME: privatize to AsmPrinter. 1608 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 1609 return OutContext.GetOrCreateSymbol 1610 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" + 1611 Twine(UID) + "_set_" + Twine(MBBID)); 1612 } 1613 1614 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with 1615 /// global value name as its base, with the specified suffix, and where the 1616 /// symbol is forced to have private linkage if ForcePrivate is true. 1617 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV, 1618 StringRef Suffix, 1619 bool ForcePrivate) const { 1620 SmallString<60> NameStr; 1621 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate); 1622 NameStr.append(Suffix.begin(), Suffix.end()); 1623 return OutContext.GetOrCreateSymbol(NameStr.str()); 1624 } 1625 1626 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified 1627 /// ExternalSymbol. 1628 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 1629 SmallString<60> NameStr; 1630 Mang->getNameWithPrefix(NameStr, Sym); 1631 return OutContext.GetOrCreateSymbol(NameStr.str()); 1632 } 1633 1634 1635 1636 /// PrintParentLoopComment - Print comments about parent loops of this one. 1637 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 1638 unsigned FunctionNumber) { 1639 if (Loop == 0) return; 1640 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 1641 OS.indent(Loop->getLoopDepth()*2) 1642 << "Parent Loop BB" << FunctionNumber << "_" 1643 << Loop->getHeader()->getNumber() 1644 << " Depth=" << Loop->getLoopDepth() << '\n'; 1645 } 1646 1647 1648 /// PrintChildLoopComment - Print comments about child loops within 1649 /// the loop for this basic block, with nesting. 1650 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 1651 unsigned FunctionNumber) { 1652 // Add child loop information 1653 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){ 1654 OS.indent((*CL)->getLoopDepth()*2) 1655 << "Child Loop BB" << FunctionNumber << "_" 1656 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth() 1657 << '\n'; 1658 PrintChildLoopComment(OS, *CL, FunctionNumber); 1659 } 1660 } 1661 1662 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks. 1663 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB, 1664 const MachineLoopInfo *LI, 1665 const AsmPrinter &AP) { 1666 // Add loop depth information 1667 const MachineLoop *Loop = LI->getLoopFor(&MBB); 1668 if (Loop == 0) return; 1669 1670 MachineBasicBlock *Header = Loop->getHeader(); 1671 assert(Header && "No header for loop"); 1672 1673 // If this block is not a loop header, just print out what is the loop header 1674 // and return. 1675 if (Header != &MBB) { 1676 AP.OutStreamer.AddComment(" in Loop: Header=BB" + 1677 Twine(AP.getFunctionNumber())+"_" + 1678 Twine(Loop->getHeader()->getNumber())+ 1679 " Depth="+Twine(Loop->getLoopDepth())); 1680 return; 1681 } 1682 1683 // Otherwise, it is a loop header. Print out information about child and 1684 // parent loops. 1685 raw_ostream &OS = AP.OutStreamer.GetCommentOS(); 1686 1687 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 1688 1689 OS << "=>"; 1690 OS.indent(Loop->getLoopDepth()*2-2); 1691 1692 OS << "This "; 1693 if (Loop->empty()) 1694 OS << "Inner "; 1695 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 1696 1697 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 1698 } 1699 1700 1701 /// EmitBasicBlockStart - This method prints the label for the specified 1702 /// MachineBasicBlock, an alignment (if present) and a comment describing 1703 /// it if appropriate. 1704 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const { 1705 // Emit an alignment directive for this block, if needed. 1706 if (unsigned Align = MBB->getAlignment()) 1707 EmitAlignment(Log2_32(Align)); 1708 1709 // If the block has its address taken, emit any labels that were used to 1710 // reference the block. It is possible that there is more than one label 1711 // here, because multiple LLVM BB's may have been RAUW'd to this block after 1712 // the references were generated. 1713 if (MBB->hasAddressTaken()) { 1714 const BasicBlock *BB = MBB->getBasicBlock(); 1715 if (isVerbose()) 1716 OutStreamer.AddComment("Block address taken"); 1717 1718 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB); 1719 1720 for (unsigned i = 0, e = Syms.size(); i != e; ++i) 1721 OutStreamer.EmitLabel(Syms[i]); 1722 } 1723 1724 // Print the main label for the block. 1725 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) { 1726 if (isVerbose() && OutStreamer.hasRawTextSupport()) { 1727 if (const BasicBlock *BB = MBB->getBasicBlock()) 1728 if (BB->hasName()) 1729 OutStreamer.AddComment("%" + BB->getName()); 1730 1731 EmitBasicBlockLoopComments(*MBB, LI, *this); 1732 1733 // NOTE: Want this comment at start of line, don't emit with AddComment. 1734 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" + 1735 Twine(MBB->getNumber()) + ":"); 1736 } 1737 } else { 1738 if (isVerbose()) { 1739 if (const BasicBlock *BB = MBB->getBasicBlock()) 1740 if (BB->hasName()) 1741 OutStreamer.AddComment("%" + BB->getName()); 1742 EmitBasicBlockLoopComments(*MBB, LI, *this); 1743 } 1744 1745 OutStreamer.EmitLabel(MBB->getSymbol()); 1746 } 1747 } 1748 1749 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const { 1750 MCSymbolAttr Attr = MCSA_Invalid; 1751 1752 switch (Visibility) { 1753 default: break; 1754 case GlobalValue::HiddenVisibility: 1755 Attr = MAI->getHiddenVisibilityAttr(); 1756 break; 1757 case GlobalValue::ProtectedVisibility: 1758 Attr = MAI->getProtectedVisibilityAttr(); 1759 break; 1760 } 1761 1762 if (Attr != MCSA_Invalid) 1763 OutStreamer.EmitSymbolAttribute(Sym, Attr); 1764 } 1765 1766 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 1767 /// exactly one predecessor and the control transfer mechanism between 1768 /// the predecessor and this block is a fall-through. 1769 bool AsmPrinter:: 1770 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 1771 // If this is a landing pad, it isn't a fall through. If it has no preds, 1772 // then nothing falls through to it. 1773 if (MBB->isLandingPad() || MBB->pred_empty()) 1774 return false; 1775 1776 // If there isn't exactly one predecessor, it can't be a fall through. 1777 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI; 1778 ++PI2; 1779 if (PI2 != MBB->pred_end()) 1780 return false; 1781 1782 // The predecessor has to be immediately before this block. 1783 const MachineBasicBlock *Pred = *PI; 1784 1785 if (!Pred->isLayoutSuccessor(MBB)) 1786 return false; 1787 1788 // If the block is completely empty, then it definitely does fall through. 1789 if (Pred->empty()) 1790 return true; 1791 1792 // Otherwise, check the last instruction. 1793 const MachineInstr &LastInst = Pred->back(); 1794 return !LastInst.getDesc().isBarrier(); 1795 } 1796 1797 1798 1799 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) { 1800 if (!S->usesMetadata()) 1801 return 0; 1802 1803 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 1804 gcp_map_type::iterator GCPI = GCMap.find(S); 1805 if (GCPI != GCMap.end()) 1806 return GCPI->second; 1807 1808 const char *Name = S->getName().c_str(); 1809 1810 for (GCMetadataPrinterRegistry::iterator 1811 I = GCMetadataPrinterRegistry::begin(), 1812 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 1813 if (strcmp(Name, I->getName()) == 0) { 1814 GCMetadataPrinter *GMP = I->instantiate(); 1815 GMP->S = S; 1816 GCMap.insert(std::make_pair(S, GMP)); 1817 return GMP; 1818 } 1819 1820 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 1821 return 0; 1822 } 1823 1824