blob: ed51e10d220055b742686ddb51303d613b2c7aac [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/MachineConstantPool.h"
20#include "llvm/CodeGen/MachineJumpTableInfo.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Mangler.h"
23#include "llvm/Support/MathExtras.h"
24#include "llvm/Support/Streams.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"
Evan Cheng6fb06762007-11-09 01:32:10 +000029#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include <cerrno>
31using namespace llvm;
32
33static cl::opt<bool>
34AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
35
36char AsmPrinter::ID = 0;
37AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
38 const TargetAsmInfo *T)
Evan Cheng477013c2007-10-14 05:57:21 +000039 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040{}
41
42std::string AsmPrinter::getSectionForFunction(const Function &F) const {
43 return TAI->getTextSection();
44}
45
46
47/// SwitchToTextSection - Switch to the specified text section of the executable
48/// if we are not already in it!
49///
50void AsmPrinter::SwitchToTextSection(const char *NewSection,
51 const GlobalValue *GV) {
52 std::string NS;
53 if (GV && GV->hasSection())
54 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
55 else
56 NS = NewSection;
57
58 // If we're already in this section, we're done.
59 if (CurrentSection == NS) return;
60
61 // Close the current section, if applicable.
62 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
63 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
64
65 CurrentSection = NS;
66
67 if (!CurrentSection.empty())
68 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
69}
70
71/// SwitchToDataSection - Switch to the specified data section of the executable
72/// if we are not already in it!
73///
74void AsmPrinter::SwitchToDataSection(const char *NewSection,
75 const GlobalValue *GV) {
76 std::string NS;
77 if (GV && GV->hasSection())
78 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
79 else
80 NS = NewSection;
81
82 // If we're already in this section, we're done.
83 if (CurrentSection == NS) return;
84
85 // Close the current section, if applicable.
86 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
87 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
88
89 CurrentSection = NS;
90
91 if (!CurrentSection.empty())
92 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
93}
94
95
96bool AsmPrinter::doInitialization(Module &M) {
97 Mang = new Mangler(M, TAI->getGlobalPrefix());
98
99 if (!M.getModuleInlineAsm().empty())
100 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
101 << M.getModuleInlineAsm()
102 << "\n" << TAI->getCommentString()
103 << " End of file scope inline assembly\n";
104
105 SwitchToDataSection(""); // Reset back to no section.
106
107 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
108 MMI->AnalyzeModule(M);
109 }
110
111 return false;
112}
113
114bool AsmPrinter::doFinalization(Module &M) {
115 if (TAI->getWeakRefDirective()) {
116 if (!ExtWeakSymbols.empty())
117 SwitchToDataSection("");
118
119 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
120 e = ExtWeakSymbols.end(); i != e; ++i) {
121 const GlobalValue *GV = *i;
122 std::string Name = Mang->getValueName(GV);
123 O << TAI->getWeakRefDirective() << Name << "\n";
124 }
125 }
126
127 if (TAI->getSetDirective()) {
128 if (!M.alias_empty())
129 SwitchToTextSection(TAI->getTextSection());
130
131 O << "\n";
132 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
133 I!=E; ++I) {
134 std::string Name = Mang->getValueName(I);
135 std::string Target;
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000136
137 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
138 Target = Mang->getValueName(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000140 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 O << "\t.globl\t" << Name << "\n";
142 else if (I->hasWeakLinkage())
143 O << TAI->getWeakRefDirective() << Name << "\n";
144 else if (!I->hasInternalLinkage())
145 assert(0 && "Invalid alias linkage");
146
147 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000148
149 // If the aliasee has external weak linkage it can be referenced only by
150 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
151 // weak reference in such case.
152 if (GV->hasExternalWeakLinkage())
153 if (TAI->getWeakRefDirective())
154 O << TAI->getWeakRefDirective() << Target << "\n";
155 else
156 O << "\t.globl\t" << Target << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 }
158 }
159
160 delete Mang; Mang = 0;
161 return false;
162}
163
Bill Wendlinge9ecdcf2007-09-18 09:10:16 +0000164std::string AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
Bill Wendlingef9211a2007-09-18 01:47:22 +0000165 assert(MF && "No machine function?");
Bill Wendlingd2144aa2007-09-18 05:03:44 +0000166 return Mang->makeNameProper(MF->getFunction()->getName() + ".eh",
167 TAI->getGlobalPrefix());
Bill Wendlingef9211a2007-09-18 01:47:22 +0000168}
169
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
171 // What's my mangled name?
172 CurrentFnName = Mang->getValueName(MF.getFunction());
Evan Cheng477013c2007-10-14 05:57:21 +0000173 IncrementFunctionNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174}
175
176/// EmitConstantPool - Print to the current output stream assembly
177/// representations of the constants in the constant pool MCP. This is
178/// used to print out constants which have been "spilled to memory" by
179/// the code generator.
180///
181void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
182 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
183 if (CP.empty()) return;
184
185 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
186 // in special sections.
187 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
188 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
189 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
190 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
191 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
192 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
193 MachineConstantPoolEntry CPE = CP[i];
194 const Type *Ty = CPE.getType();
195 if (TAI->getFourByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000196 TM.getTargetData()->getABITypeSize(Ty) == 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 FourByteCPs.push_back(std::make_pair(CPE, i));
198 else if (TAI->getEightByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000199 TM.getTargetData()->getABITypeSize(Ty) == 8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 EightByteCPs.push_back(std::make_pair(CPE, i));
201 else if (TAI->getSixteenByteConstantSection() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000202 TM.getTargetData()->getABITypeSize(Ty) == 16)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 SixteenByteCPs.push_back(std::make_pair(CPE, i));
204 else
205 OtherCPs.push_back(std::make_pair(CPE, i));
206 }
207
208 unsigned Alignment = MCP->getConstantPoolAlignment();
209 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
210 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
211 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
212 SixteenByteCPs);
213 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
214}
215
216void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
217 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
218 if (CP.empty()) return;
219
220 SwitchToDataSection(Section);
221 EmitAlignment(Alignment);
222 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Evan Cheng477013c2007-10-14 05:57:21 +0000223 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
224 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
226 if (CP[i].first.isMachineConstantPoolEntry())
227 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
228 else
229 EmitGlobalConstant(CP[i].first.Val.ConstVal);
230 if (i != e-1) {
231 const Type *Ty = CP[i].first.getType();
232 unsigned EntSize =
Duncan Sands8157ef42007-11-05 00:04:43 +0000233 TM.getTargetData()->getABITypeSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
235 // Emit inter-object padding for alignment.
236 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
237 }
238 }
239}
240
241/// EmitJumpTableInfo - Print assembly representations of the jump tables used
242/// by the current function to the current output stream.
243///
244void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
245 MachineFunction &MF) {
246 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
247 if (JT.empty()) return;
248 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
249
250 // Use JumpTableDirective otherwise honor the entry size from the jump table
251 // info.
252 const char *JTEntryDirective = TAI->getJumpTableDirective();
253 bool HadJTEntryDirective = JTEntryDirective != NULL;
254 if (!HadJTEntryDirective) {
255 JTEntryDirective = MJTI->getEntrySize() == 4 ?
256 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
257 }
258
259 // Pick the directive to use to print the jump table entries, and switch to
260 // the appropriate section.
261 TargetLowering *LoweringInfo = TM.getTargetLowering();
262
263 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
264 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
265 !JumpTableDataSection) {
266 // In PIC mode, we need to emit the jump table to the same section as the
267 // function body itself, otherwise the label differences won't make sense.
268 // We should also do if the section name is NULL.
269 const Function *F = MF.getFunction();
270 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
271 } else {
272 SwitchToDataSection(JumpTableDataSection);
273 }
274
275 EmitAlignment(Log2_32(MJTI->getAlignment()));
276
277 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
278 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
279
280 // If this jump table was deleted, ignore it.
281 if (JTBBs.empty()) continue;
282
283 // For PIC codegen, if possible we want to use the SetDirective to reduce
284 // the number of relocations the assembler will generate for the jump table.
285 // Set directives are all printed before the jump table itself.
Evan Cheng6fb06762007-11-09 01:32:10 +0000286 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 if (TAI->getSetDirective() && IsPic)
288 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Evan Cheng6fb06762007-11-09 01:32:10 +0000289 if (EmittedSets.insert(JTBBs[ii]))
290 printPICJumpTableSetLabel(i, JTBBs[ii]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291
292 // On some targets (e.g. darwin) we want to emit two consequtive labels
293 // before each jump table. The first label is never referenced, but tells
294 // the assembler and linker the extents of the jump table object. The
295 // second label is actually referenced by the code.
296 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
Evan Cheng477013c2007-10-14 05:57:21 +0000297 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298
Evan Cheng477013c2007-10-14 05:57:21 +0000299 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
300 << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301
302 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
303 O << JTEntryDirective << ' ';
304 // If we have emitted set directives for the jump table entries, print
305 // them rather than the entries themselves. If we're emitting PIC, then
306 // emit the table entries as differences between two text section labels.
307 // If we're emitting non-PIC code, then emit the entries as direct
308 // references to the target basic blocks.
309 if (!EmittedSets.empty()) {
Evan Cheng477013c2007-10-14 05:57:21 +0000310 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
311 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 } else if (IsPic) {
313 printBasicBlockLabel(JTBBs[ii], false, false);
314 // If the arch uses custom Jump Table directives, don't calc relative to
315 // JT
316 if (!HadJTEntryDirective)
317 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
Evan Cheng477013c2007-10-14 05:57:21 +0000318 << getFunctionNumber() << '_' << i;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 } else {
320 printBasicBlockLabel(JTBBs[ii], false, false);
321 }
322 O << '\n';
323 }
324 }
325}
326
327/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
328/// special global used by LLVM. If so, emit it and return true, otherwise
329/// do nothing and return false.
330bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Andrew Lenharth61d35f52007-08-22 19:33:11 +0000331 if (GV->getName() == "llvm.used") {
332 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
333 EmitLLVMUsedList(GV->getInitializer());
334 return true;
335 }
336
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 // Ignore debug and non-emitted data.
338 if (GV->getSection() == "llvm.metadata") return true;
339
340 if (!GV->hasAppendingLinkage()) return false;
341
342 assert(GV->hasInitializer() && "Not a special LLVM global!");
343
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 const TargetData *TD = TM.getTargetData();
345 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
346 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
347 SwitchToDataSection(TAI->getStaticCtorsSection());
348 EmitAlignment(Align, 0);
349 EmitXXStructorList(GV->getInitializer());
350 return true;
351 }
352
353 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
354 SwitchToDataSection(TAI->getStaticDtorsSection());
355 EmitAlignment(Align, 0);
356 EmitXXStructorList(GV->getInitializer());
357 return true;
358 }
359
360 return false;
361}
362
363/// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
364/// global in the specified llvm.used list as being used with this directive.
365void AsmPrinter::EmitLLVMUsedList(Constant *List) {
366 const char *Directive = TAI->getUsedDirective();
367
368 // Should be an array of 'sbyte*'.
369 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
370 if (InitList == 0) return;
371
372 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
373 O << Directive;
374 EmitConstantValueOnly(InitList->getOperand(i));
375 O << "\n";
376 }
377}
378
379/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
380/// function pointers, ignoring the init priority.
381void AsmPrinter::EmitXXStructorList(Constant *List) {
382 // Should be an array of '{ int, void ()* }' structs. The first value is the
383 // init priority, which we ignore.
384 if (!isa<ConstantArray>(List)) return;
385 ConstantArray *InitList = cast<ConstantArray>(List);
386 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
387 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
388 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
389
390 if (CS->getOperand(1)->isNullValue())
391 return; // Found a null terminator, exit printing.
392 // Emit the function pointer.
393 EmitGlobalConstant(CS->getOperand(1));
394 }
395}
396
397/// getGlobalLinkName - Returns the asm/link name of of the specified
398/// global variable. Should be overridden by each target asm printer to
399/// generate the appropriate value.
400const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
401 std::string LinkName;
402
403 if (isa<Function>(GV)) {
404 LinkName += TAI->getFunctionAddrPrefix();
405 LinkName += Mang->getValueName(GV);
406 LinkName += TAI->getFunctionAddrSuffix();
407 } else {
408 LinkName += TAI->getGlobalVarAddrPrefix();
409 LinkName += Mang->getValueName(GV);
410 LinkName += TAI->getGlobalVarAddrSuffix();
411 }
412
413 return LinkName;
414}
415
416/// EmitExternalGlobal - Emit the external reference to a global variable.
417/// Should be overridden if an indirect reference should be used.
418void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
419 O << getGlobalLinkName(GV);
420}
421
422
423
424//===----------------------------------------------------------------------===//
425/// LEB 128 number encoding.
426
427/// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
428/// representing an unsigned leb128 value.
429void AsmPrinter::PrintULEB128(unsigned Value) const {
430 do {
431 unsigned Byte = Value & 0x7f;
432 Value >>= 7;
433 if (Value) Byte |= 0x80;
434 O << "0x" << std::hex << Byte << std::dec;
435 if (Value) O << ", ";
436 } while (Value);
437}
438
439/// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
440/// value.
441unsigned AsmPrinter::SizeULEB128(unsigned Value) {
442 unsigned Size = 0;
443 do {
444 Value >>= 7;
445 Size += sizeof(int8_t);
446 } while (Value);
447 return Size;
448}
449
450/// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
451/// representing a signed leb128 value.
452void AsmPrinter::PrintSLEB128(int Value) const {
453 int Sign = Value >> (8 * sizeof(Value) - 1);
454 bool IsMore;
455
456 do {
457 unsigned Byte = Value & 0x7f;
458 Value >>= 7;
459 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
460 if (IsMore) Byte |= 0x80;
461 O << "0x" << std::hex << Byte << std::dec;
462 if (IsMore) O << ", ";
463 } while (IsMore);
464}
465
466/// SizeSLEB128 - Compute the number of bytes required for a signed leb128
467/// value.
468unsigned AsmPrinter::SizeSLEB128(int Value) {
469 unsigned Size = 0;
470 int Sign = Value >> (8 * sizeof(Value) - 1);
471 bool IsMore;
472
473 do {
474 unsigned Byte = Value & 0x7f;
475 Value >>= 7;
476 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
477 Size += sizeof(int8_t);
478 } while (IsMore);
479 return Size;
480}
481
482//===--------------------------------------------------------------------===//
483// Emission and print routines
484//
485
486/// PrintHex - Print a value as a hexidecimal value.
487///
488void AsmPrinter::PrintHex(int Value) const {
489 O << "0x" << std::hex << Value << std::dec;
490}
491
492/// EOL - Print a newline character to asm stream. If a comment is present
493/// then it will be printed first. Comments should not contain '\n'.
494void AsmPrinter::EOL() const {
495 O << "\n";
496}
497void AsmPrinter::EOL(const std::string &Comment) const {
498 if (AsmVerbose && !Comment.empty()) {
499 O << "\t"
500 << TAI->getCommentString()
501 << " "
502 << Comment;
503 }
504 O << "\n";
505}
506
507/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
508/// unsigned leb128 value.
509void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
510 if (TAI->hasLEB128()) {
511 O << "\t.uleb128\t"
512 << Value;
513 } else {
514 O << TAI->getData8bitsDirective();
515 PrintULEB128(Value);
516 }
517}
518
519/// EmitSLEB128Bytes - print an assembler byte data directive to compose a
520/// signed leb128 value.
521void AsmPrinter::EmitSLEB128Bytes(int Value) const {
522 if (TAI->hasLEB128()) {
523 O << "\t.sleb128\t"
524 << Value;
525 } else {
526 O << TAI->getData8bitsDirective();
527 PrintSLEB128(Value);
528 }
529}
530
531/// EmitInt8 - Emit a byte directive and value.
532///
533void AsmPrinter::EmitInt8(int Value) const {
534 O << TAI->getData8bitsDirective();
535 PrintHex(Value & 0xFF);
536}
537
538/// EmitInt16 - Emit a short directive and value.
539///
540void AsmPrinter::EmitInt16(int Value) const {
541 O << TAI->getData16bitsDirective();
542 PrintHex(Value & 0xFFFF);
543}
544
545/// EmitInt32 - Emit a long directive and value.
546///
547void AsmPrinter::EmitInt32(int Value) const {
548 O << TAI->getData32bitsDirective();
549 PrintHex(Value);
550}
551
552/// EmitInt64 - Emit a long long directive and value.
553///
554void AsmPrinter::EmitInt64(uint64_t Value) const {
555 if (TAI->getData64bitsDirective()) {
556 O << TAI->getData64bitsDirective();
557 PrintHex(Value);
558 } else {
559 if (TM.getTargetData()->isBigEndian()) {
560 EmitInt32(unsigned(Value >> 32)); O << "\n";
561 EmitInt32(unsigned(Value));
562 } else {
563 EmitInt32(unsigned(Value)); O << "\n";
564 EmitInt32(unsigned(Value >> 32));
565 }
566 }
567}
568
569/// toOctal - Convert the low order bits of X into an octal digit.
570///
571static inline char toOctal(int X) {
572 return (X&7)+'0';
573}
574
575/// printStringChar - Print a char, escaped if necessary.
576///
577static void printStringChar(std::ostream &O, unsigned char C) {
578 if (C == '"') {
579 O << "\\\"";
580 } else if (C == '\\') {
581 O << "\\\\";
582 } else if (isprint(C)) {
583 O << C;
584 } else {
585 switch(C) {
586 case '\b': O << "\\b"; break;
587 case '\f': O << "\\f"; break;
588 case '\n': O << "\\n"; break;
589 case '\r': O << "\\r"; break;
590 case '\t': O << "\\t"; break;
591 default:
592 O << '\\';
593 O << toOctal(C >> 6);
594 O << toOctal(C >> 3);
595 O << toOctal(C >> 0);
596 break;
597 }
598 }
599}
600
601/// EmitString - Emit a string with quotes and a null terminator.
602/// Special characters are emitted properly.
603/// \literal (Eg. '\t') \endliteral
604void AsmPrinter::EmitString(const std::string &String) const {
605 const char* AscizDirective = TAI->getAscizDirective();
606 if (AscizDirective)
607 O << AscizDirective;
608 else
609 O << TAI->getAsciiDirective();
610 O << "\"";
611 for (unsigned i = 0, N = String.size(); i < N; ++i) {
612 unsigned char C = String[i];
613 printStringChar(O, C);
614 }
615 if (AscizDirective)
616 O << "\"";
617 else
618 O << "\\0\"";
619}
620
621
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000622/// EmitFile - Emit a .file directive.
623void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
624 O << "\t.file\t" << Number << " \"";
625 for (unsigned i = 0, N = Name.size(); i < N; ++i) {
626 unsigned char C = Name[i];
627 printStringChar(O, C);
628 }
629 O << "\"";
630}
631
632
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633//===----------------------------------------------------------------------===//
634
635// EmitAlignment - Emit an alignment directive to the specified power of
636// two boundary. For example, if you pass in 3 here, you will get an 8
637// byte alignment. If a global value is specified, and if that global has
638// an explicit alignment requested, it will unconditionally override the
639// alignment request. However, if ForcedAlignBits is specified, this value
640// has final say: the ultimate alignment will be the max of ForcedAlignBits
641// and the alignment computed with NumBits and the global.
642//
643// The algorithm is:
644// Align = NumBits;
645// if (GV && GV->hasalignment) Align = GV->getalignment();
646// Align = std::max(Align, ForcedAlignBits);
647//
648void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Chengc1f41aa2007-07-25 23:35:07 +0000649 unsigned ForcedAlignBits, bool UseFillExpr,
650 unsigned FillValue) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 if (GV && GV->getAlignment())
652 NumBits = Log2_32(GV->getAlignment());
653 NumBits = std::max(NumBits, ForcedAlignBits);
654
655 if (NumBits == 0) return; // No need to emit alignment.
656 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
Evan Chengc1f41aa2007-07-25 23:35:07 +0000657 O << TAI->getAlignDirective() << NumBits;
658 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
659 O << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660}
661
662
663/// EmitZeros - Emit a block of zeros.
664///
665void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
666 if (NumZeros) {
667 if (TAI->getZeroDirective()) {
668 O << TAI->getZeroDirective() << NumZeros;
669 if (TAI->getZeroDirectiveSuffix())
670 O << TAI->getZeroDirectiveSuffix();
671 O << "\n";
672 } else {
673 for (; NumZeros; --NumZeros)
674 O << TAI->getData8bitsDirective() << "0\n";
675 }
676 }
677}
678
679// Print out the specified constant, without a storage class. Only the
680// constants valid in constant expressions can occur here.
681void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
682 if (CV->isNullValue() || isa<UndefValue>(CV))
683 O << "0";
684 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
685 O << CI->getZExtValue();
686 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
687 // This is a constant address for a global variable or function. Use the
688 // name of the variable or function as the address value, possibly
689 // decorating it with GlobalVarAddrPrefix/Suffix or
690 // FunctionAddrPrefix/Suffix (these all default to "" )
691 if (isa<Function>(GV)) {
692 O << TAI->getFunctionAddrPrefix()
693 << Mang->getValueName(GV)
694 << TAI->getFunctionAddrSuffix();
695 } else {
696 O << TAI->getGlobalVarAddrPrefix()
697 << Mang->getValueName(GV)
698 << TAI->getGlobalVarAddrSuffix();
699 }
700 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
701 const TargetData *TD = TM.getTargetData();
702 unsigned Opcode = CE->getOpcode();
703 switch (Opcode) {
704 case Instruction::GetElementPtr: {
705 // generate a symbolic expression for the byte address
706 const Constant *ptrVal = CE->getOperand(0);
707 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
708 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
709 idxVec.size())) {
710 if (Offset)
711 O << "(";
712 EmitConstantValueOnly(ptrVal);
713 if (Offset > 0)
714 O << ") + " << Offset;
715 else if (Offset < 0)
716 O << ") - " << -Offset;
717 } else {
718 EmitConstantValueOnly(ptrVal);
719 }
720 break;
721 }
722 case Instruction::Trunc:
723 case Instruction::ZExt:
724 case Instruction::SExt:
725 case Instruction::FPTrunc:
726 case Instruction::FPExt:
727 case Instruction::UIToFP:
728 case Instruction::SIToFP:
729 case Instruction::FPToUI:
730 case Instruction::FPToSI:
731 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
732 break;
733 case Instruction::BitCast:
734 return EmitConstantValueOnly(CE->getOperand(0));
735
736 case Instruction::IntToPtr: {
737 // Handle casts to pointers by changing them into casts to the appropriate
738 // integer type. This promotes constant folding and simplifies this code.
739 Constant *Op = CE->getOperand(0);
740 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
741 return EmitConstantValueOnly(Op);
742 }
743
744
745 case Instruction::PtrToInt: {
746 // Support only foldable casts to/from pointers that can be eliminated by
747 // changing the pointer to the appropriately sized integer type.
748 Constant *Op = CE->getOperand(0);
749 const Type *Ty = CE->getType();
750
751 // We can emit the pointer value into this slot if the slot is an
752 // integer slot greater or equal to the size of the pointer.
753 if (Ty->isInteger() &&
Duncan Sands8157ef42007-11-05 00:04:43 +0000754 TD->getABITypeSize(Ty) >= TD->getABITypeSize(Op->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755 return EmitConstantValueOnly(Op);
756
757 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
758 EmitConstantValueOnly(Op);
759 break;
760 }
761 case Instruction::Add:
762 case Instruction::Sub:
763 O << "(";
764 EmitConstantValueOnly(CE->getOperand(0));
765 O << (Opcode==Instruction::Add ? ") + (" : ") - (");
766 EmitConstantValueOnly(CE->getOperand(1));
767 O << ")";
768 break;
769 default:
770 assert(0 && "Unsupported operator!");
771 }
772 } else {
773 assert(0 && "Unknown constant value!");
774 }
775}
776
777/// printAsCString - Print the specified array as a C compatible string, only if
778/// the predicate isString is true.
779///
780static void printAsCString(std::ostream &O, const ConstantArray *CVA,
781 unsigned LastElt) {
782 assert(CVA->isString() && "Array is not string compatible!");
783
784 O << "\"";
785 for (unsigned i = 0; i != LastElt; ++i) {
786 unsigned char C =
787 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
788 printStringChar(O, C);
789 }
790 O << "\"";
791}
792
793/// EmitString - Emit a zero-byte-terminated string constant.
794///
795void AsmPrinter::EmitString(const ConstantArray *CVA) const {
796 unsigned NumElts = CVA->getNumOperands();
797 if (TAI->getAscizDirective() && NumElts &&
798 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
799 O << TAI->getAscizDirective();
800 printAsCString(O, CVA, NumElts-1);
801 } else {
802 O << TAI->getAsciiDirective();
803 printAsCString(O, CVA, NumElts);
804 }
805 O << "\n";
806}
807
808/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Duncan Sands8157ef42007-11-05 00:04:43 +0000809/// If Packed is false, pad to the ABI size.
810void AsmPrinter::EmitGlobalConstant(const Constant *CV, bool Packed) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 const TargetData *TD = TM.getTargetData();
Duncan Sands8157ef42007-11-05 00:04:43 +0000812 unsigned Size = Packed ?
813 TD->getTypeStoreSize(CV->getType()) : TD->getABITypeSize(CV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814
815 if (CV->isNullValue() || isa<UndefValue>(CV)) {
Duncan Sands8157ef42007-11-05 00:04:43 +0000816 EmitZeros(Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 return;
818 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
819 if (CVA->isString()) {
820 EmitString(CVA);
821 } else { // Not a string. Print the values in successive locations
Duncan Sands8157ef42007-11-05 00:04:43 +0000822 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
823 EmitGlobalConstant(CVA->getOperand(i), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 }
825 return;
826 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
827 // Print the fields in successive locations. Pad to align if needed!
828 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
829 uint64_t sizeSoFar = 0;
830 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
831 const Constant* field = CVS->getOperand(i);
832
833 // Check if padding is needed and insert one or more 0s.
Duncan Sands8157ef42007-11-05 00:04:43 +0000834 uint64_t fieldSize = TD->getTypeStoreSize(field->getType());
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000835 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 - cvsLayout->getElementOffset(i)) - fieldSize;
837 sizeSoFar += fieldSize + padSize;
838
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000839 // Now print the actual field value without ABI size padding.
840 EmitGlobalConstant(field, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841
Duncan Sandsc15d58c2007-11-05 18:03:02 +0000842 // Insert padding - this may include padding to increase the size of the
843 // current field up to the ABI size (if the struct is not packed) as well
844 // as padding to ensure that the next field starts at the right offset.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 EmitZeros(padSize);
846 }
847 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
848 "Layout of constant struct may be incorrect!");
849 return;
850 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
851 // FP Constants are printed as integer constants to avoid losing
852 // precision...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 if (CFP->getType() == Type::DoubleTy) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000854 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000855 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 if (TAI->getData64bitsDirective())
Dale Johannesen1616e902007-09-11 18:32:33 +0000857 O << TAI->getData64bitsDirective() << i << "\t"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 << TAI->getCommentString() << " double value: " << Val << "\n";
859 else if (TD->isBigEndian()) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000860 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 << "\t" << TAI->getCommentString()
862 << " double most significant word " << Val << "\n";
Dale Johannesen1616e902007-09-11 18:32:33 +0000863 O << TAI->getData32bitsDirective() << unsigned(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 << "\t" << TAI->getCommentString()
865 << " double least significant word " << Val << "\n";
866 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +0000867 O << TAI->getData32bitsDirective() << unsigned(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 << "\t" << TAI->getCommentString()
869 << " double least significant word " << Val << "\n";
Dale Johannesen1616e902007-09-11 18:32:33 +0000870 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 << "\t" << TAI->getCommentString()
872 << " double most significant word " << Val << "\n";
873 }
874 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000875 } else if (CFP->getType() == Type::FloatTy) {
Dale Johannesen1616e902007-09-11 18:32:33 +0000876 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
877 O << TAI->getData32bitsDirective()
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000878 << CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
880 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000881 } else if (CFP->getType() == Type::X86_FP80Ty) {
882 // all long double variants are printed as hex
Dale Johannesen693aa822007-09-26 23:20:33 +0000883 // api needed to prevent premature destruction
884 APInt api = CFP->getValueAPF().convertToAPInt();
885 const uint64_t *p = api.getRawData();
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000886 if (TD->isBigEndian()) {
887 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
888 << "\t" << TAI->getCommentString()
889 << " long double most significant halfword\n";
890 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
891 << "\t" << TAI->getCommentString()
892 << " long double next halfword\n";
893 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
894 << "\t" << TAI->getCommentString()
895 << " long double next halfword\n";
896 O << TAI->getData16bitsDirective() << uint16_t(p[0])
897 << "\t" << TAI->getCommentString()
898 << " long double next halfword\n";
899 O << TAI->getData16bitsDirective() << uint16_t(p[1])
900 << "\t" << TAI->getCommentString()
901 << " long double least significant halfword\n";
902 } else {
903 O << TAI->getData16bitsDirective() << uint16_t(p[1])
904 << "\t" << TAI->getCommentString()
905 << " long double least significant halfword\n";
906 O << TAI->getData16bitsDirective() << uint16_t(p[0])
907 << "\t" << TAI->getCommentString()
908 << " long double next halfword\n";
909 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
910 << "\t" << TAI->getCommentString()
911 << " long double next halfword\n";
912 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
913 << "\t" << TAI->getCommentString()
914 << " long double next halfword\n";
915 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
916 << "\t" << TAI->getCommentString()
917 << " long double most significant halfword\n";
918 }
Duncan Sands8157ef42007-11-05 00:04:43 +0000919 EmitZeros(Size - TD->getTypeStoreSize(Type::X86_FP80Ty));
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000920 return;
Dale Johannesend3b6af32007-10-11 23:32:15 +0000921 } else if (CFP->getType() == Type::PPC_FP128Ty) {
922 // all long double variants are printed as hex
923 // api needed to prevent premature destruction
924 APInt api = CFP->getValueAPF().convertToAPInt();
925 const uint64_t *p = api.getRawData();
926 if (TD->isBigEndian()) {
927 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
928 << "\t" << TAI->getCommentString()
929 << " long double most significant word\n";
930 O << TAI->getData32bitsDirective() << uint32_t(p[0])
931 << "\t" << TAI->getCommentString()
932 << " long double next word\n";
933 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
934 << "\t" << TAI->getCommentString()
935 << " long double next word\n";
936 O << TAI->getData32bitsDirective() << uint32_t(p[1])
937 << "\t" << TAI->getCommentString()
938 << " long double least significant word\n";
939 } else {
940 O << TAI->getData32bitsDirective() << uint32_t(p[1])
941 << "\t" << TAI->getCommentString()
942 << " long double least significant word\n";
943 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
944 << "\t" << TAI->getCommentString()
945 << " long double next word\n";
946 O << TAI->getData32bitsDirective() << uint32_t(p[0])
947 << "\t" << TAI->getCommentString()
948 << " long double next word\n";
949 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
950 << "\t" << TAI->getCommentString()
951 << " long double most significant word\n";
952 }
953 return;
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000954 } else assert(0 && "Floating point constant type not handled");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955 } else if (CV->getType() == Type::Int64Ty) {
956 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
957 uint64_t Val = CI->getZExtValue();
958
959 if (TAI->getData64bitsDirective())
960 O << TAI->getData64bitsDirective() << Val << "\n";
961 else if (TD->isBigEndian()) {
962 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
963 << "\t" << TAI->getCommentString()
964 << " Double-word most significant word " << Val << "\n";
965 O << TAI->getData32bitsDirective() << unsigned(Val)
966 << "\t" << TAI->getCommentString()
967 << " Double-word least significant word " << Val << "\n";
968 } else {
969 O << TAI->getData32bitsDirective() << unsigned(Val)
970 << "\t" << TAI->getCommentString()
971 << " Double-word least significant word " << Val << "\n";
972 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
973 << "\t" << TAI->getCommentString()
974 << " Double-word most significant word " << Val << "\n";
975 }
976 return;
977 }
978 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
979 const VectorType *PTy = CP->getType();
980
981 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
Duncan Sands8157ef42007-11-05 00:04:43 +0000982 EmitGlobalConstant(CP->getOperand(I), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983
984 return;
985 }
986
987 const Type *type = CV->getType();
988 printDataDirective(type);
989 EmitConstantValueOnly(CV);
990 O << "\n";
991}
992
993void
994AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
995 // Target doesn't support this yet!
996 abort();
997}
998
999/// PrintSpecial - Print information related to the specified machine instr
1000/// that is independent of the operand, and may be independent of the instr
1001/// itself. This can be useful for portably encoding the comment character
1002/// or other bits of target-specific knowledge into the asmstrings. The
1003/// syntax used is ${:comment}. Targets can override this to add support
1004/// for their own strange codes.
1005void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
1006 if (!strcmp(Code, "private")) {
1007 O << TAI->getPrivateGlobalPrefix();
1008 } else if (!strcmp(Code, "comment")) {
1009 O << TAI->getCommentString();
1010 } else if (!strcmp(Code, "uid")) {
1011 // Assign a unique ID to this machine instruction.
1012 static const MachineInstr *LastMI = 0;
1013 static const Function *F = 0;
1014 static unsigned Counter = 0U-1;
1015
1016 // Comparing the address of MI isn't sufficient, because machineinstrs may
1017 // be allocated to the same address across functions.
1018 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1019
1020 // If this is a new machine instruction, bump the counter.
1021 if (LastMI != MI || F != ThisF) {
1022 ++Counter;
1023 LastMI = MI;
1024 F = ThisF;
1025 }
1026 O << Counter;
1027 } else {
1028 cerr << "Unknown special formatter '" << Code
1029 << "' for machine instr: " << *MI;
1030 exit(1);
1031 }
1032}
1033
1034
1035/// printInlineAsm - This method formats and prints the specified machine
1036/// instruction that is an inline asm.
1037void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1038 unsigned NumOperands = MI->getNumOperands();
1039
1040 // Count the number of register definitions.
1041 unsigned NumDefs = 0;
Dan Gohman38a9a9f2007-09-14 20:33:02 +00001042 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 ++NumDefs)
1044 assert(NumDefs != NumOperands-1 && "No asm string?");
1045
1046 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1047
1048 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1049 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1050
1051 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
1052 if (AsmStr[0] == 0) {
1053 O << "\n"; // Tab already printed, avoid double indenting next instr.
1054 return;
1055 }
1056
1057 O << TAI->getInlineAsmStart() << "\n\t";
1058
1059 // The variant of the current asmprinter.
1060 int AsmPrinterVariant = TAI->getAssemblerDialect();
1061
1062 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1063 const char *LastEmitted = AsmStr; // One past the last character emitted.
1064
1065 while (*LastEmitted) {
1066 switch (*LastEmitted) {
1067 default: {
1068 // Not a special case, emit the string section literally.
1069 const char *LiteralEnd = LastEmitted+1;
1070 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1071 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1072 ++LiteralEnd;
1073 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1074 O.write(LastEmitted, LiteralEnd-LastEmitted);
1075 LastEmitted = LiteralEnd;
1076 break;
1077 }
1078 case '\n':
1079 ++LastEmitted; // Consume newline character.
1080 O << "\n"; // Indent code with newline.
1081 break;
1082 case '$': {
1083 ++LastEmitted; // Consume '$' character.
1084 bool Done = true;
1085
1086 // Handle escapes.
1087 switch (*LastEmitted) {
1088 default: Done = false; break;
1089 case '$': // $$ -> $
1090 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1091 O << '$';
1092 ++LastEmitted; // Consume second '$' character.
1093 break;
1094 case '(': // $( -> same as GCC's { character.
1095 ++LastEmitted; // Consume '(' character.
1096 if (CurVariant != -1) {
1097 cerr << "Nested variants found in inline asm string: '"
1098 << AsmStr << "'\n";
1099 exit(1);
1100 }
1101 CurVariant = 0; // We're in the first variant now.
1102 break;
1103 case '|':
1104 ++LastEmitted; // consume '|' character.
1105 if (CurVariant == -1) {
1106 cerr << "Found '|' character outside of variant in inline asm "
1107 << "string: '" << AsmStr << "'\n";
1108 exit(1);
1109 }
1110 ++CurVariant; // We're in the next variant.
1111 break;
1112 case ')': // $) -> same as GCC's } char.
1113 ++LastEmitted; // consume ')' character.
1114 if (CurVariant == -1) {
1115 cerr << "Found '}' character outside of variant in inline asm "
1116 << "string: '" << AsmStr << "'\n";
1117 exit(1);
1118 }
1119 CurVariant = -1;
1120 break;
1121 }
1122 if (Done) break;
1123
1124 bool HasCurlyBraces = false;
1125 if (*LastEmitted == '{') { // ${variable}
1126 ++LastEmitted; // Consume '{' character.
1127 HasCurlyBraces = true;
1128 }
1129
1130 const char *IDStart = LastEmitted;
1131 char *IDEnd;
1132 errno = 0;
1133 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1134 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1135 cerr << "Bad $ operand number in inline asm string: '"
1136 << AsmStr << "'\n";
1137 exit(1);
1138 }
1139 LastEmitted = IDEnd;
1140
1141 char Modifier[2] = { 0, 0 };
1142
1143 if (HasCurlyBraces) {
1144 // If we have curly braces, check for a modifier character. This
1145 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1146 if (*LastEmitted == ':') {
1147 ++LastEmitted; // Consume ':' character.
1148 if (*LastEmitted == 0) {
1149 cerr << "Bad ${:} expression in inline asm string: '"
1150 << AsmStr << "'\n";
1151 exit(1);
1152 }
1153
1154 Modifier[0] = *LastEmitted;
1155 ++LastEmitted; // Consume modifier character.
1156 }
1157
1158 if (*LastEmitted != '}') {
1159 cerr << "Bad ${} expression in inline asm string: '"
1160 << AsmStr << "'\n";
1161 exit(1);
1162 }
1163 ++LastEmitted; // Consume '}' character.
1164 }
1165
1166 if ((unsigned)Val >= NumOperands-1) {
1167 cerr << "Invalid $ operand number in inline asm string: '"
1168 << AsmStr << "'\n";
1169 exit(1);
1170 }
1171
1172 // Okay, we finally have a value number. Ask the target to print this
1173 // operand!
1174 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1175 unsigned OpNo = 1;
1176
1177 bool Error = false;
1178
1179 // Scan to find the machine operand number for the operand.
1180 for (; Val; --Val) {
1181 if (OpNo >= MI->getNumOperands()) break;
1182 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1183 OpNo += (OpFlags >> 3) + 1;
1184 }
1185
1186 if (OpNo >= MI->getNumOperands()) {
1187 Error = true;
1188 } else {
1189 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1190 ++OpNo; // Skip over the ID number.
1191
Dale Johannesencfb19e62007-11-05 21:20:28 +00001192 if (Modifier[0]=='l') // labels are target independent
1193 printBasicBlockLabel(MI->getOperand(OpNo).getMachineBasicBlock(),
1194 false, false);
1195 else {
1196 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1197 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1198 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1199 Modifier[0] ? Modifier : 0);
1200 } else {
1201 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1202 Modifier[0] ? Modifier : 0);
1203 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 }
1205 }
1206 if (Error) {
1207 cerr << "Invalid operand found in inline asm: '"
1208 << AsmStr << "'\n";
1209 MI->dump();
1210 exit(1);
1211 }
1212 }
1213 break;
1214 }
1215 }
1216 }
1217 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1218}
1219
1220/// printLabel - This method prints a local label used by debug and
1221/// exception handling tables.
1222void AsmPrinter::printLabel(const MachineInstr *MI) const {
1223 O << "\n"
1224 << TAI->getPrivateGlobalPrefix()
1225 << "label"
1226 << MI->getOperand(0).getImmedValue()
1227 << ":\n";
1228}
1229
1230/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1231/// instruction, using the specified assembler variant. Targets should
1232/// overried this to format as appropriate.
1233bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1234 unsigned AsmVariant, const char *ExtraCode) {
1235 // Target doesn't support this yet!
1236 return true;
1237}
1238
1239bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1240 unsigned AsmVariant,
1241 const char *ExtraCode) {
1242 // Target doesn't support this yet!
1243 return true;
1244}
1245
1246/// printBasicBlockLabel - This method prints the label for the specified
1247/// MachineBasicBlock
1248void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1249 bool printColon,
1250 bool printComment) const {
Evan Cheng477013c2007-10-14 05:57:21 +00001251 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << "_"
1252 << MBB->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253 if (printColon)
1254 O << ':';
1255 if (printComment && MBB->getBasicBlock())
Dan Gohman0912cda2007-07-30 15:06:25 +00001256 O << '\t' << TAI->getCommentString() << ' '
1257 << MBB->getBasicBlock()->getName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258}
1259
Evan Cheng6fb06762007-11-09 01:32:10 +00001260/// printPICJumpTableSetLabel - This method prints a set label for the
1261/// specified MachineBasicBlock for a jumptable entry.
1262void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1263 const MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 if (!TAI->getSetDirective())
1265 return;
1266
1267 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001268 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 printBasicBlockLabel(MBB, false, false);
Evan Cheng477013c2007-10-14 05:57:21 +00001270 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1271 << '_' << uid << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272}
1273
Evan Cheng6fb06762007-11-09 01:32:10 +00001274void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1275 const MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 if (!TAI->getSetDirective())
1277 return;
1278
1279 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001280 << getFunctionNumber() << '_' << uid << '_' << uid2
1281 << "_set_" << MBB->getNumber() << ',';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 printBasicBlockLabel(MBB, false, false);
Evan Cheng477013c2007-10-14 05:57:21 +00001283 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1284 << '_' << uid << '_' << uid2 << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285}
1286
1287/// printDataDirective - This method prints the asm directive for the
1288/// specified type.
1289void AsmPrinter::printDataDirective(const Type *type) {
1290 const TargetData *TD = TM.getTargetData();
1291 switch (type->getTypeID()) {
1292 case Type::IntegerTyID: {
1293 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1294 if (BitWidth <= 8)
1295 O << TAI->getData8bitsDirective();
1296 else if (BitWidth <= 16)
1297 O << TAI->getData16bitsDirective();
1298 else if (BitWidth <= 32)
1299 O << TAI->getData32bitsDirective();
1300 else if (BitWidth <= 64) {
1301 assert(TAI->getData64bitsDirective() &&
1302 "Target cannot handle 64-bit constant exprs!");
1303 O << TAI->getData64bitsDirective();
1304 }
1305 break;
1306 }
1307 case Type::PointerTyID:
1308 if (TD->getPointerSize() == 8) {
1309 assert(TAI->getData64bitsDirective() &&
1310 "Target cannot handle 64-bit pointer exprs!");
1311 O << TAI->getData64bitsDirective();
1312 } else {
1313 O << TAI->getData32bitsDirective();
1314 }
1315 break;
1316 case Type::FloatTyID: case Type::DoubleTyID:
Dale Johannesen3b5303b2007-09-28 18:06:58 +00001317 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 assert (0 && "Should have already output floating point constant.");
1319 default:
1320 assert (0 && "Can't handle printing this type of thing");
1321 break;
1322 }
1323}
1324