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