Remove attribution from file headers, per discussion on llvmdev.
[oota-llvm.git] / lib / CodeGen / AsmPrinter.cpp
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/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"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include <cerrno>
31 using namespace llvm;
32
33 static cl::opt<bool>
34 AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
35
36 char AsmPrinter::ID = 0;
37 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
38                        const TargetAsmInfo *T)
39   : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
40 {}
41
42 std::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 ///
50 void 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 ///
74 void 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
96 bool 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
114 bool 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;
136
137       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
138       Target = Mang->getValueName(GV);
139       
140       if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
141         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";
148
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";
157     }
158   }
159
160   delete Mang; Mang = 0;
161   return false;
162 }
163
164 std::string AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
165   assert(MF && "No machine function?");
166   return Mang->makeNameProper(MF->getFunction()->getName() + ".eh",
167                               TAI->getGlobalPrefix());
168 }
169
170 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
171   // What's my mangled name?
172   CurrentFnName = Mang->getValueName(MF.getFunction());
173   IncrementFunctionNumber();
174 }
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 ///
181 void 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() &&
196         TM.getTargetData()->getABITypeSize(Ty) == 4)
197       FourByteCPs.push_back(std::make_pair(CPE, i));
198     else if (TAI->getEightByteConstantSection() &&
199              TM.getTargetData()->getABITypeSize(Ty) == 8)
200       EightByteCPs.push_back(std::make_pair(CPE, i));
201     else if (TAI->getSixteenByteConstantSection() &&
202              TM.getTargetData()->getABITypeSize(Ty) == 16)
203       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
216 void 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) {
223     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
224       << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
225     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 =
233         TM.getTargetData()->getABITypeSize(Ty);
234       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 ///
244 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
245                                    MachineFunction &MF) {
246   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
247   if (JT.empty()) return;
248
249   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
250   
251   // Pick the directive to use to print the jump table entries, and switch to 
252   // the appropriate section.
253   TargetLowering *LoweringInfo = TM.getTargetLowering();
254
255   const char* JumpTableDataSection = TAI->getJumpTableDataSection();  
256   if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
257      !JumpTableDataSection) {
258     // In PIC mode, we need to emit the jump table to the same section as the
259     // function body itself, otherwise the label differences won't make sense.
260     // We should also do if the section name is NULL.
261     const Function *F = MF.getFunction();
262     SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
263   } else {
264     SwitchToDataSection(JumpTableDataSection);
265   }
266   
267   EmitAlignment(Log2_32(MJTI->getAlignment()));
268   
269   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
270     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
271     
272     // If this jump table was deleted, ignore it. 
273     if (JTBBs.empty()) continue;
274
275     // For PIC codegen, if possible we want to use the SetDirective to reduce
276     // the number of relocations the assembler will generate for the jump table.
277     // Set directives are all printed before the jump table itself.
278     SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
279     if (TAI->getSetDirective() && IsPic)
280       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
281         if (EmittedSets.insert(JTBBs[ii]))
282           printPICJumpTableSetLabel(i, JTBBs[ii]);
283     
284     // On some targets (e.g. darwin) we want to emit two consequtive labels
285     // before each jump table.  The first label is never referenced, but tells
286     // the assembler and linker the extents of the jump table object.  The
287     // second label is actually referenced by the code.
288     if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
289       O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
290     
291     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
292       << '_' << i << ":\n";
293     
294     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
295       printPICJumpTableEntry(MJTI, JTBBs[ii], i);
296       O << '\n';
297     }
298   }
299 }
300
301 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
302                                         const MachineBasicBlock *MBB,
303                                         unsigned uid)  const {
304   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
305   
306   // Use JumpTableDirective otherwise honor the entry size from the jump table
307   // info.
308   const char *JTEntryDirective = TAI->getJumpTableDirective();
309   bool HadJTEntryDirective = JTEntryDirective != NULL;
310   if (!HadJTEntryDirective) {
311     JTEntryDirective = MJTI->getEntrySize() == 4 ?
312       TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
313   }
314
315   O << JTEntryDirective << ' ';
316
317   // If we have emitted set directives for the jump table entries, print 
318   // them rather than the entries themselves.  If we're emitting PIC, then
319   // emit the table entries as differences between two text section labels.
320   // If we're emitting non-PIC code, then emit the entries as direct
321   // references to the target basic blocks.
322   if (IsPic) {
323     if (TAI->getSetDirective()) {
324       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
325         << '_' << uid << "_set_" << MBB->getNumber();
326     } else {
327       printBasicBlockLabel(MBB, false, false);
328       // If the arch uses custom Jump Table directives, don't calc relative to
329       // JT
330       if (!HadJTEntryDirective) 
331         O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
332           << getFunctionNumber() << '_' << uid;
333     }
334   } else {
335     printBasicBlockLabel(MBB, false, false);
336   }
337 }
338
339
340 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
341 /// special global used by LLVM.  If so, emit it and return true, otherwise
342 /// do nothing and return false.
343 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
344   if (GV->getName() == "llvm.used") {
345     if (TAI->getUsedDirective() != 0)    // No need to emit this at all.
346       EmitLLVMUsedList(GV->getInitializer());
347     return true;
348   }
349
350   // Ignore debug and non-emitted data.
351   if (GV->getSection() == "llvm.metadata") return true;
352   
353   if (!GV->hasAppendingLinkage()) return false;
354
355   assert(GV->hasInitializer() && "Not a special LLVM global!");
356   
357   const TargetData *TD = TM.getTargetData();
358   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
359   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
360     SwitchToDataSection(TAI->getStaticCtorsSection());
361     EmitAlignment(Align, 0);
362     EmitXXStructorList(GV->getInitializer());
363     return true;
364   } 
365   
366   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
367     SwitchToDataSection(TAI->getStaticDtorsSection());
368     EmitAlignment(Align, 0);
369     EmitXXStructorList(GV->getInitializer());
370     return true;
371   }
372   
373   return false;
374 }
375
376 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
377 /// global in the specified llvm.used list as being used with this directive.
378 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
379   const char *Directive = TAI->getUsedDirective();
380
381   // Should be an array of 'sbyte*'.
382   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
383   if (InitList == 0) return;
384   
385   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
386     O << Directive;
387     EmitConstantValueOnly(InitList->getOperand(i));
388     O << "\n";
389   }
390 }
391
392 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
393 /// function pointers, ignoring the init priority.
394 void AsmPrinter::EmitXXStructorList(Constant *List) {
395   // Should be an array of '{ int, void ()* }' structs.  The first value is the
396   // init priority, which we ignore.
397   if (!isa<ConstantArray>(List)) return;
398   ConstantArray *InitList = cast<ConstantArray>(List);
399   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
400     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
401       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
402
403       if (CS->getOperand(1)->isNullValue())
404         return;  // Found a null terminator, exit printing.
405       // Emit the function pointer.
406       EmitGlobalConstant(CS->getOperand(1));
407     }
408 }
409
410 /// getGlobalLinkName - Returns the asm/link name of of the specified
411 /// global variable.  Should be overridden by each target asm printer to
412 /// generate the appropriate value.
413 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
414   std::string LinkName;
415   
416   if (isa<Function>(GV)) {
417     LinkName += TAI->getFunctionAddrPrefix();
418     LinkName += Mang->getValueName(GV);
419     LinkName += TAI->getFunctionAddrSuffix();
420   } else {
421     LinkName += TAI->getGlobalVarAddrPrefix();
422     LinkName += Mang->getValueName(GV);
423     LinkName += TAI->getGlobalVarAddrSuffix();
424   }  
425   
426   return LinkName;
427 }
428
429 /// EmitExternalGlobal - Emit the external reference to a global variable.
430 /// Should be overridden if an indirect reference should be used.
431 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
432   O << getGlobalLinkName(GV);
433 }
434
435
436
437 //===----------------------------------------------------------------------===//
438 /// LEB 128 number encoding.
439
440 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
441 /// representing an unsigned leb128 value.
442 void AsmPrinter::PrintULEB128(unsigned Value) const {
443   do {
444     unsigned Byte = Value & 0x7f;
445     Value >>= 7;
446     if (Value) Byte |= 0x80;
447     O << "0x" << std::hex << Byte << std::dec;
448     if (Value) O << ", ";
449   } while (Value);
450 }
451
452 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
453 /// value.
454 unsigned AsmPrinter::SizeULEB128(unsigned Value) {
455   unsigned Size = 0;
456   do {
457     Value >>= 7;
458     Size += sizeof(int8_t);
459   } while (Value);
460   return Size;
461 }
462
463 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
464 /// representing a signed leb128 value.
465 void AsmPrinter::PrintSLEB128(int Value) const {
466   int Sign = Value >> (8 * sizeof(Value) - 1);
467   bool IsMore;
468   
469   do {
470     unsigned Byte = Value & 0x7f;
471     Value >>= 7;
472     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
473     if (IsMore) Byte |= 0x80;
474     O << "0x" << std::hex << Byte << std::dec;
475     if (IsMore) O << ", ";
476   } while (IsMore);
477 }
478
479 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
480 /// value.
481 unsigned AsmPrinter::SizeSLEB128(int Value) {
482   unsigned Size = 0;
483   int Sign = Value >> (8 * sizeof(Value) - 1);
484   bool IsMore;
485   
486   do {
487     unsigned Byte = Value & 0x7f;
488     Value >>= 7;
489     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
490     Size += sizeof(int8_t);
491   } while (IsMore);
492   return Size;
493 }
494
495 //===--------------------------------------------------------------------===//
496 // Emission and print routines
497 //
498
499 /// PrintHex - Print a value as a hexidecimal value.
500 ///
501 void AsmPrinter::PrintHex(int Value) const { 
502   O << "0x" << std::hex << Value << std::dec;
503 }
504
505 /// EOL - Print a newline character to asm stream.  If a comment is present
506 /// then it will be printed first.  Comments should not contain '\n'.
507 void AsmPrinter::EOL() const {
508   O << "\n";
509 }
510 void AsmPrinter::EOL(const std::string &Comment) const {
511   if (AsmVerbose && !Comment.empty()) {
512     O << "\t"
513       << TAI->getCommentString()
514       << " "
515       << Comment;
516   }
517   O << "\n";
518 }
519
520 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
521 /// unsigned leb128 value.
522 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
523   if (TAI->hasLEB128()) {
524     O << "\t.uleb128\t"
525       << Value;
526   } else {
527     O << TAI->getData8bitsDirective();
528     PrintULEB128(Value);
529   }
530 }
531
532 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
533 /// signed leb128 value.
534 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
535   if (TAI->hasLEB128()) {
536     O << "\t.sleb128\t"
537       << Value;
538   } else {
539     O << TAI->getData8bitsDirective();
540     PrintSLEB128(Value);
541   }
542 }
543
544 /// EmitInt8 - Emit a byte directive and value.
545 ///
546 void AsmPrinter::EmitInt8(int Value) const {
547   O << TAI->getData8bitsDirective();
548   PrintHex(Value & 0xFF);
549 }
550
551 /// EmitInt16 - Emit a short directive and value.
552 ///
553 void AsmPrinter::EmitInt16(int Value) const {
554   O << TAI->getData16bitsDirective();
555   PrintHex(Value & 0xFFFF);
556 }
557
558 /// EmitInt32 - Emit a long directive and value.
559 ///
560 void AsmPrinter::EmitInt32(int Value) const {
561   O << TAI->getData32bitsDirective();
562   PrintHex(Value);
563 }
564
565 /// EmitInt64 - Emit a long long directive and value.
566 ///
567 void AsmPrinter::EmitInt64(uint64_t Value) const {
568   if (TAI->getData64bitsDirective()) {
569     O << TAI->getData64bitsDirective();
570     PrintHex(Value);
571   } else {
572     if (TM.getTargetData()->isBigEndian()) {
573       EmitInt32(unsigned(Value >> 32)); O << "\n";
574       EmitInt32(unsigned(Value));
575     } else {
576       EmitInt32(unsigned(Value)); O << "\n";
577       EmitInt32(unsigned(Value >> 32));
578     }
579   }
580 }
581
582 /// toOctal - Convert the low order bits of X into an octal digit.
583 ///
584 static inline char toOctal(int X) {
585   return (X&7)+'0';
586 }
587
588 /// printStringChar - Print a char, escaped if necessary.
589 ///
590 static void printStringChar(std::ostream &O, unsigned char C) {
591   if (C == '"') {
592     O << "\\\"";
593   } else if (C == '\\') {
594     O << "\\\\";
595   } else if (isprint(C)) {
596     O << C;
597   } else {
598     switch(C) {
599     case '\b': O << "\\b"; break;
600     case '\f': O << "\\f"; break;
601     case '\n': O << "\\n"; break;
602     case '\r': O << "\\r"; break;
603     case '\t': O << "\\t"; break;
604     default:
605       O << '\\';
606       O << toOctal(C >> 6);
607       O << toOctal(C >> 3);
608       O << toOctal(C >> 0);
609       break;
610     }
611   }
612 }
613
614 /// EmitString - Emit a string with quotes and a null terminator.
615 /// Special characters are emitted properly.
616 /// \literal (Eg. '\t') \endliteral
617 void AsmPrinter::EmitString(const std::string &String) const {
618   const char* AscizDirective = TAI->getAscizDirective();
619   if (AscizDirective)
620     O << AscizDirective;
621   else
622     O << TAI->getAsciiDirective();
623   O << "\"";
624   for (unsigned i = 0, N = String.size(); i < N; ++i) {
625     unsigned char C = String[i];
626     printStringChar(O, C);
627   }
628   if (AscizDirective)
629     O << "\"";
630   else
631     O << "\\0\"";
632 }
633
634
635 /// EmitFile - Emit a .file directive.
636 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
637   O << "\t.file\t" << Number << " \"";
638   for (unsigned i = 0, N = Name.size(); i < N; ++i) {
639     unsigned char C = Name[i];
640     printStringChar(O, C);
641   }
642   O << "\"";
643 }
644
645
646 //===----------------------------------------------------------------------===//
647
648 // EmitAlignment - Emit an alignment directive to the specified power of
649 // two boundary.  For example, if you pass in 3 here, you will get an 8
650 // byte alignment.  If a global value is specified, and if that global has
651 // an explicit alignment requested, it will unconditionally override the
652 // alignment request.  However, if ForcedAlignBits is specified, this value
653 // has final say: the ultimate alignment will be the max of ForcedAlignBits
654 // and the alignment computed with NumBits and the global.
655 //
656 // The algorithm is:
657 //     Align = NumBits;
658 //     if (GV && GV->hasalignment) Align = GV->getalignment();
659 //     Align = std::max(Align, ForcedAlignBits);
660 //
661 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
662                                unsigned ForcedAlignBits, bool UseFillExpr,
663                                unsigned FillValue) const {
664   if (GV && GV->getAlignment())
665     NumBits = Log2_32(GV->getAlignment());
666   NumBits = std::max(NumBits, ForcedAlignBits);
667   
668   if (NumBits == 0) return;   // No need to emit alignment.
669   if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
670   O << TAI->getAlignDirective() << NumBits;
671   if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
672   O << "\n";
673 }
674
675     
676 /// EmitZeros - Emit a block of zeros.
677 ///
678 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
679   if (NumZeros) {
680     if (TAI->getZeroDirective()) {
681       O << TAI->getZeroDirective() << NumZeros;
682       if (TAI->getZeroDirectiveSuffix())
683         O << TAI->getZeroDirectiveSuffix();
684       O << "\n";
685     } else {
686       for (; NumZeros; --NumZeros)
687         O << TAI->getData8bitsDirective() << "0\n";
688     }
689   }
690 }
691
692 // Print out the specified constant, without a storage class.  Only the
693 // constants valid in constant expressions can occur here.
694 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
695   if (CV->isNullValue() || isa<UndefValue>(CV))
696     O << "0";
697   else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
698     O << CI->getZExtValue();
699   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
700     // This is a constant address for a global variable or function. Use the
701     // name of the variable or function as the address value, possibly
702     // decorating it with GlobalVarAddrPrefix/Suffix or
703     // FunctionAddrPrefix/Suffix (these all default to "" )
704     if (isa<Function>(GV)) {
705       O << TAI->getFunctionAddrPrefix()
706         << Mang->getValueName(GV)
707         << TAI->getFunctionAddrSuffix();
708     } else {
709       O << TAI->getGlobalVarAddrPrefix()
710         << Mang->getValueName(GV)
711         << TAI->getGlobalVarAddrSuffix();
712     }
713   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
714     const TargetData *TD = TM.getTargetData();
715     unsigned Opcode = CE->getOpcode();    
716     switch (Opcode) {
717     case Instruction::GetElementPtr: {
718       // generate a symbolic expression for the byte address
719       const Constant *ptrVal = CE->getOperand(0);
720       SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
721       if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
722                                                 idxVec.size())) {
723         if (Offset)
724           O << "(";
725         EmitConstantValueOnly(ptrVal);
726         if (Offset > 0)
727           O << ") + " << Offset;
728         else if (Offset < 0)
729           O << ") - " << -Offset;
730       } else {
731         EmitConstantValueOnly(ptrVal);
732       }
733       break;
734     }
735     case Instruction::Trunc:
736     case Instruction::ZExt:
737     case Instruction::SExt:
738     case Instruction::FPTrunc:
739     case Instruction::FPExt:
740     case Instruction::UIToFP:
741     case Instruction::SIToFP:
742     case Instruction::FPToUI:
743     case Instruction::FPToSI:
744       assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
745       break;
746     case Instruction::BitCast:
747       return EmitConstantValueOnly(CE->getOperand(0));
748
749     case Instruction::IntToPtr: {
750       // Handle casts to pointers by changing them into casts to the appropriate
751       // integer type.  This promotes constant folding and simplifies this code.
752       Constant *Op = CE->getOperand(0);
753       Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
754       return EmitConstantValueOnly(Op);
755     }
756       
757       
758     case Instruction::PtrToInt: {
759       // Support only foldable casts to/from pointers that can be eliminated by
760       // changing the pointer to the appropriately sized integer type.
761       Constant *Op = CE->getOperand(0);
762       const Type *Ty = CE->getType();
763
764       // We can emit the pointer value into this slot if the slot is an
765       // integer slot greater or equal to the size of the pointer.
766       if (Ty->isInteger() &&
767           TD->getABITypeSize(Ty) >= TD->getABITypeSize(Op->getType()))
768         return EmitConstantValueOnly(Op);
769       
770       assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
771       EmitConstantValueOnly(Op);
772       break;
773     }
774     case Instruction::Add:
775     case Instruction::Sub:
776     case Instruction::And:
777     case Instruction::Or:
778     case Instruction::Xor:
779       O << "(";
780       EmitConstantValueOnly(CE->getOperand(0));
781       O << ")";
782       switch (Opcode) {
783       case Instruction::Add:
784        O << " + ";
785        break;
786       case Instruction::Sub:
787        O << " - ";
788        break;
789       case Instruction::And:
790        O << " & ";
791        break;
792       case Instruction::Or:
793        O << " | ";
794        break;
795       case Instruction::Xor:
796        O << " ^ ";
797        break;
798       default:
799        break;
800       }
801       O << "(";
802       EmitConstantValueOnly(CE->getOperand(1));
803       O << ")";
804       break;
805     default:
806       assert(0 && "Unsupported operator!");
807     }
808   } else {
809     assert(0 && "Unknown constant value!");
810   }
811 }
812
813 /// printAsCString - Print the specified array as a C compatible string, only if
814 /// the predicate isString is true.
815 ///
816 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
817                            unsigned LastElt) {
818   assert(CVA->isString() && "Array is not string compatible!");
819
820   O << "\"";
821   for (unsigned i = 0; i != LastElt; ++i) {
822     unsigned char C =
823         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
824     printStringChar(O, C);
825   }
826   O << "\"";
827 }
828
829 /// EmitString - Emit a zero-byte-terminated string constant.
830 ///
831 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
832   unsigned NumElts = CVA->getNumOperands();
833   if (TAI->getAscizDirective() && NumElts && 
834       cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
835     O << TAI->getAscizDirective();
836     printAsCString(O, CVA, NumElts-1);
837   } else {
838     O << TAI->getAsciiDirective();
839     printAsCString(O, CVA, NumElts);
840   }
841   O << "\n";
842 }
843
844 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
845 /// If Packed is false, pad to the ABI size.
846 void AsmPrinter::EmitGlobalConstant(const Constant *CV, bool Packed) {
847   const TargetData *TD = TM.getTargetData();
848   unsigned Size = Packed ?
849     TD->getTypeStoreSize(CV->getType()) : TD->getABITypeSize(CV->getType());
850
851   if (CV->isNullValue() || isa<UndefValue>(CV)) {
852     EmitZeros(Size);
853     return;
854   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
855     if (CVA->isString()) {
856       EmitString(CVA);
857     } else { // Not a string.  Print the values in successive locations
858       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
859         EmitGlobalConstant(CVA->getOperand(i), false);
860     }
861     return;
862   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
863     // Print the fields in successive locations. Pad to align if needed!
864     const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
865     uint64_t sizeSoFar = 0;
866     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
867       const Constant* field = CVS->getOperand(i);
868
869       // Check if padding is needed and insert one or more 0s.
870       uint64_t fieldSize = TD->getTypeStoreSize(field->getType());
871       uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
872                           - cvsLayout->getElementOffset(i)) - fieldSize;
873       sizeSoFar += fieldSize + padSize;
874
875       // Now print the actual field value without ABI size padding.
876       EmitGlobalConstant(field, true);
877
878       // Insert padding - this may include padding to increase the size of the
879       // current field up to the ABI size (if the struct is not packed) as well
880       // as padding to ensure that the next field starts at the right offset.
881       EmitZeros(padSize);
882     }
883     assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
884            "Layout of constant struct may be incorrect!");
885     return;
886   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
887     // FP Constants are printed as integer constants to avoid losing
888     // precision...
889     if (CFP->getType() == Type::DoubleTy) {
890       double Val = CFP->getValueAPF().convertToDouble();  // for comment only
891       uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
892       if (TAI->getData64bitsDirective())
893         O << TAI->getData64bitsDirective() << i << "\t"
894           << TAI->getCommentString() << " double value: " << Val << "\n";
895       else if (TD->isBigEndian()) {
896         O << TAI->getData32bitsDirective() << unsigned(i >> 32)
897           << "\t" << TAI->getCommentString()
898           << " double most significant word " << Val << "\n";
899         O << TAI->getData32bitsDirective() << unsigned(i)
900           << "\t" << TAI->getCommentString()
901           << " double least significant word " << Val << "\n";
902       } else {
903         O << TAI->getData32bitsDirective() << unsigned(i)
904           << "\t" << TAI->getCommentString()
905           << " double least significant word " << Val << "\n";
906         O << TAI->getData32bitsDirective() << unsigned(i >> 32)
907           << "\t" << TAI->getCommentString()
908           << " double most significant word " << Val << "\n";
909       }
910       return;
911     } else if (CFP->getType() == Type::FloatTy) {
912       float Val = CFP->getValueAPF().convertToFloat();  // for comment only
913       O << TAI->getData32bitsDirective()
914         << CFP->getValueAPF().convertToAPInt().getZExtValue()
915         << "\t" << TAI->getCommentString() << " float " << Val << "\n";
916       return;
917     } else if (CFP->getType() == Type::X86_FP80Ty) {
918       // all long double variants are printed as hex
919       // api needed to prevent premature destruction
920       APInt api = CFP->getValueAPF().convertToAPInt();
921       const uint64_t *p = api.getRawData();
922       if (TD->isBigEndian()) {
923         O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
924           << "\t" << TAI->getCommentString()
925           << " long double most significant halfword\n";
926         O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
927           << "\t" << TAI->getCommentString()
928           << " long double next halfword\n";
929         O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
930           << "\t" << TAI->getCommentString()
931           << " long double next halfword\n";
932         O << TAI->getData16bitsDirective() << uint16_t(p[0])
933           << "\t" << TAI->getCommentString()
934           << " long double next halfword\n";
935         O << TAI->getData16bitsDirective() << uint16_t(p[1])
936           << "\t" << TAI->getCommentString()
937           << " long double least significant halfword\n";
938        } else {
939         O << TAI->getData16bitsDirective() << uint16_t(p[1])
940           << "\t" << TAI->getCommentString()
941           << " long double least significant halfword\n";
942         O << TAI->getData16bitsDirective() << uint16_t(p[0])
943           << "\t" << TAI->getCommentString()
944           << " long double next halfword\n";
945         O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
946           << "\t" << TAI->getCommentString()
947           << " long double next halfword\n";
948         O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
949           << "\t" << TAI->getCommentString()
950           << " long double next halfword\n";
951         O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
952           << "\t" << TAI->getCommentString()
953           << " long double most significant halfword\n";
954       }
955       EmitZeros(Size - TD->getTypeStoreSize(Type::X86_FP80Ty));
956       return;
957     } else if (CFP->getType() == Type::PPC_FP128Ty) {
958       // all long double variants are printed as hex
959       // api needed to prevent premature destruction
960       APInt api = CFP->getValueAPF().convertToAPInt();
961       const uint64_t *p = api.getRawData();
962       if (TD->isBigEndian()) {
963         O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
964           << "\t" << TAI->getCommentString()
965           << " long double most significant word\n";
966         O << TAI->getData32bitsDirective() << uint32_t(p[0])
967           << "\t" << TAI->getCommentString()
968           << " long double next word\n";
969         O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
970           << "\t" << TAI->getCommentString()
971           << " long double next word\n";
972         O << TAI->getData32bitsDirective() << uint32_t(p[1])
973           << "\t" << TAI->getCommentString()
974           << " long double least significant word\n";
975        } else {
976         O << TAI->getData32bitsDirective() << uint32_t(p[1])
977           << "\t" << TAI->getCommentString()
978           << " long double least significant word\n";
979         O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
980           << "\t" << TAI->getCommentString()
981           << " long double next word\n";
982         O << TAI->getData32bitsDirective() << uint32_t(p[0])
983           << "\t" << TAI->getCommentString()
984           << " long double next word\n";
985         O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
986           << "\t" << TAI->getCommentString()
987           << " long double most significant word\n";
988       }
989       return;
990     } else assert(0 && "Floating point constant type not handled");
991   } else if (CV->getType() == Type::Int64Ty) {
992     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
993       uint64_t Val = CI->getZExtValue();
994
995       if (TAI->getData64bitsDirective())
996         O << TAI->getData64bitsDirective() << Val << "\n";
997       else if (TD->isBigEndian()) {
998         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
999           << "\t" << TAI->getCommentString()
1000           << " Double-word most significant word " << Val << "\n";
1001         O << TAI->getData32bitsDirective() << unsigned(Val)
1002           << "\t" << TAI->getCommentString()
1003           << " Double-word least significant word " << Val << "\n";
1004       } else {
1005         O << TAI->getData32bitsDirective() << unsigned(Val)
1006           << "\t" << TAI->getCommentString()
1007           << " Double-word least significant word " << Val << "\n";
1008         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1009           << "\t" << TAI->getCommentString()
1010           << " Double-word most significant word " << Val << "\n";
1011       }
1012       return;
1013     }
1014   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1015     const VectorType *PTy = CP->getType();
1016     
1017     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1018       EmitGlobalConstant(CP->getOperand(I), false);
1019     
1020     return;
1021   }
1022
1023   const Type *type = CV->getType();
1024   printDataDirective(type);
1025   EmitConstantValueOnly(CV);
1026   O << "\n";
1027 }
1028
1029 void
1030 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1031   // Target doesn't support this yet!
1032   abort();
1033 }
1034
1035 /// PrintSpecial - Print information related to the specified machine instr
1036 /// that is independent of the operand, and may be independent of the instr
1037 /// itself.  This can be useful for portably encoding the comment character
1038 /// or other bits of target-specific knowledge into the asmstrings.  The
1039 /// syntax used is ${:comment}.  Targets can override this to add support
1040 /// for their own strange codes.
1041 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
1042   if (!strcmp(Code, "private")) {
1043     O << TAI->getPrivateGlobalPrefix();
1044   } else if (!strcmp(Code, "comment")) {
1045     O << TAI->getCommentString();
1046   } else if (!strcmp(Code, "uid")) {
1047     // Assign a unique ID to this machine instruction.
1048     static const MachineInstr *LastMI = 0;
1049     static const Function *F = 0;
1050     static unsigned Counter = 0U-1;
1051
1052     // Comparing the address of MI isn't sufficient, because machineinstrs may
1053     // be allocated to the same address across functions.
1054     const Function *ThisF = MI->getParent()->getParent()->getFunction();
1055     
1056     // If this is a new machine instruction, bump the counter.
1057     if (LastMI != MI || F != ThisF) {
1058       ++Counter;
1059       LastMI = MI;
1060       F = ThisF;
1061     }
1062     O << Counter;
1063   } else {
1064     cerr << "Unknown special formatter '" << Code
1065          << "' for machine instr: " << *MI;
1066     exit(1);
1067   }    
1068 }
1069
1070
1071 /// printInlineAsm - This method formats and prints the specified machine
1072 /// instruction that is an inline asm.
1073 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1074   unsigned NumOperands = MI->getNumOperands();
1075   
1076   // Count the number of register definitions.
1077   unsigned NumDefs = 0;
1078   for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
1079        ++NumDefs)
1080     assert(NumDefs != NumOperands-1 && "No asm string?");
1081   
1082   assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1083
1084   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1085   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1086
1087   // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
1088   if (AsmStr[0] == 0) {
1089     O << "\n";  // Tab already printed, avoid double indenting next instr.
1090     return;
1091   }
1092   
1093   O << TAI->getInlineAsmStart() << "\n\t";
1094
1095   // The variant of the current asmprinter.
1096   int AsmPrinterVariant = TAI->getAssemblerDialect();
1097
1098   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1099   const char *LastEmitted = AsmStr; // One past the last character emitted.
1100   
1101   while (*LastEmitted) {
1102     switch (*LastEmitted) {
1103     default: {
1104       // Not a special case, emit the string section literally.
1105       const char *LiteralEnd = LastEmitted+1;
1106       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1107              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1108         ++LiteralEnd;
1109       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1110         O.write(LastEmitted, LiteralEnd-LastEmitted);
1111       LastEmitted = LiteralEnd;
1112       break;
1113     }
1114     case '\n':
1115       ++LastEmitted;   // Consume newline character.
1116       O << "\n";       // Indent code with newline.
1117       break;
1118     case '$': {
1119       ++LastEmitted;   // Consume '$' character.
1120       bool Done = true;
1121
1122       // Handle escapes.
1123       switch (*LastEmitted) {
1124       default: Done = false; break;
1125       case '$':     // $$ -> $
1126         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1127           O << '$';
1128         ++LastEmitted;  // Consume second '$' character.
1129         break;
1130       case '(':             // $( -> same as GCC's { character.
1131         ++LastEmitted;      // Consume '(' character.
1132         if (CurVariant != -1) {
1133           cerr << "Nested variants found in inline asm string: '"
1134                << AsmStr << "'\n";
1135           exit(1);
1136         }
1137         CurVariant = 0;     // We're in the first variant now.
1138         break;
1139       case '|':
1140         ++LastEmitted;  // consume '|' character.
1141         if (CurVariant == -1) {
1142           cerr << "Found '|' character outside of variant in inline asm "
1143                << "string: '" << AsmStr << "'\n";
1144           exit(1);
1145         }
1146         ++CurVariant;   // We're in the next variant.
1147         break;
1148       case ')':         // $) -> same as GCC's } char.
1149         ++LastEmitted;  // consume ')' character.
1150         if (CurVariant == -1) {
1151           cerr << "Found '}' character outside of variant in inline asm "
1152                << "string: '" << AsmStr << "'\n";
1153           exit(1);
1154         }
1155         CurVariant = -1;
1156         break;
1157       }
1158       if (Done) break;
1159       
1160       bool HasCurlyBraces = false;
1161       if (*LastEmitted == '{') {     // ${variable}
1162         ++LastEmitted;               // Consume '{' character.
1163         HasCurlyBraces = true;
1164       }
1165       
1166       const char *IDStart = LastEmitted;
1167       char *IDEnd;
1168       errno = 0;
1169       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1170       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1171         cerr << "Bad $ operand number in inline asm string: '" 
1172              << AsmStr << "'\n";
1173         exit(1);
1174       }
1175       LastEmitted = IDEnd;
1176       
1177       char Modifier[2] = { 0, 0 };
1178       
1179       if (HasCurlyBraces) {
1180         // If we have curly braces, check for a modifier character.  This
1181         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1182         if (*LastEmitted == ':') {
1183           ++LastEmitted;    // Consume ':' character.
1184           if (*LastEmitted == 0) {
1185             cerr << "Bad ${:} expression in inline asm string: '" 
1186                  << AsmStr << "'\n";
1187             exit(1);
1188           }
1189           
1190           Modifier[0] = *LastEmitted;
1191           ++LastEmitted;    // Consume modifier character.
1192         }
1193         
1194         if (*LastEmitted != '}') {
1195           cerr << "Bad ${} expression in inline asm string: '" 
1196                << AsmStr << "'\n";
1197           exit(1);
1198         }
1199         ++LastEmitted;    // Consume '}' character.
1200       }
1201       
1202       if ((unsigned)Val >= NumOperands-1) {
1203         cerr << "Invalid $ operand number in inline asm string: '" 
1204              << AsmStr << "'\n";
1205         exit(1);
1206       }
1207       
1208       // Okay, we finally have a value number.  Ask the target to print this
1209       // operand!
1210       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1211         unsigned OpNo = 1;
1212
1213         bool Error = false;
1214
1215         // Scan to find the machine operand number for the operand.
1216         for (; Val; --Val) {
1217           if (OpNo >= MI->getNumOperands()) break;
1218           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1219           OpNo += (OpFlags >> 3) + 1;
1220         }
1221
1222         if (OpNo >= MI->getNumOperands()) {
1223           Error = true;
1224         } else {
1225           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1226           ++OpNo;  // Skip over the ID number.
1227
1228           if (Modifier[0]=='l')  // labels are target independent
1229             printBasicBlockLabel(MI->getOperand(OpNo).getMachineBasicBlock(), 
1230                                  false, false);
1231           else {
1232             AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1233             if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1234               Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1235                                                 Modifier[0] ? Modifier : 0);
1236             } else {
1237               Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1238                                           Modifier[0] ? Modifier : 0);
1239             }
1240           }
1241         }
1242         if (Error) {
1243           cerr << "Invalid operand found in inline asm: '"
1244                << AsmStr << "'\n";
1245           MI->dump();
1246           exit(1);
1247         }
1248       }
1249       break;
1250     }
1251     }
1252   }
1253   O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1254 }
1255
1256 /// printLabel - This method prints a local label used by debug and
1257 /// exception handling tables.
1258 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1259   O << "\n"
1260     << TAI->getPrivateGlobalPrefix()
1261     << "label"
1262     << MI->getOperand(0).getImmedValue()
1263     << ":\n";
1264 }
1265
1266 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1267 /// instruction, using the specified assembler variant.  Targets should
1268 /// overried this to format as appropriate.
1269 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1270                                  unsigned AsmVariant, const char *ExtraCode) {
1271   // Target doesn't support this yet!
1272   return true;
1273 }
1274
1275 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1276                                        unsigned AsmVariant,
1277                                        const char *ExtraCode) {
1278   // Target doesn't support this yet!
1279   return true;
1280 }
1281
1282 /// printBasicBlockLabel - This method prints the label for the specified
1283 /// MachineBasicBlock
1284 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1285                                       bool printColon,
1286                                       bool printComment) const {
1287   O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << "_"
1288     << MBB->getNumber();
1289   if (printColon)
1290     O << ':';
1291   if (printComment && MBB->getBasicBlock())
1292     O << '\t' << TAI->getCommentString() << ' '
1293       << MBB->getBasicBlock()->getName();
1294 }
1295
1296 /// printPICJumpTableSetLabel - This method prints a set label for the
1297 /// specified MachineBasicBlock for a jumptable entry.
1298 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 
1299                                            const MachineBasicBlock *MBB) const {
1300   if (!TAI->getSetDirective())
1301     return;
1302   
1303   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1304     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1305   printBasicBlockLabel(MBB, false, false);
1306   O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
1307     << '_' << uid << '\n';
1308 }
1309
1310 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1311                                            const MachineBasicBlock *MBB) const {
1312   if (!TAI->getSetDirective())
1313     return;
1314   
1315   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1316     << getFunctionNumber() << '_' << uid << '_' << uid2
1317     << "_set_" << MBB->getNumber() << ',';
1318   printBasicBlockLabel(MBB, false, false);
1319   O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
1320     << '_' << uid << '_' << uid2 << '\n';
1321 }
1322
1323 /// printDataDirective - This method prints the asm directive for the
1324 /// specified type.
1325 void AsmPrinter::printDataDirective(const Type *type) {
1326   const TargetData *TD = TM.getTargetData();
1327   switch (type->getTypeID()) {
1328   case Type::IntegerTyID: {
1329     unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1330     if (BitWidth <= 8)
1331       O << TAI->getData8bitsDirective();
1332     else if (BitWidth <= 16)
1333       O << TAI->getData16bitsDirective();
1334     else if (BitWidth <= 32)
1335       O << TAI->getData32bitsDirective();
1336     else if (BitWidth <= 64) {
1337       assert(TAI->getData64bitsDirective() &&
1338              "Target cannot handle 64-bit constant exprs!");
1339       O << TAI->getData64bitsDirective();
1340     }
1341     break;
1342   }
1343   case Type::PointerTyID:
1344     if (TD->getPointerSize() == 8) {
1345       assert(TAI->getData64bitsDirective() &&
1346              "Target cannot handle 64-bit pointer exprs!");
1347       O << TAI->getData64bitsDirective();
1348     } else {
1349       O << TAI->getData32bitsDirective();
1350     }
1351     break;
1352   case Type::FloatTyID: case Type::DoubleTyID:
1353   case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1354     assert (0 && "Should have already output floating point constant.");
1355   default:
1356     assert (0 && "Can't handle printing this type of thing");
1357     break;
1358   }
1359 }
1360