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