Fix CodeGen/Generic/2007-04-08-MultipleFrameIndices.ll and PR1308:
[oota-llvm.git] / lib / CodeGen / AsmPrinter.cpp
1 //===-- 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"
29 #include <cerrno>
30 using namespace llvm;
31
32 static cl::opt<bool>
33 AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
34
35 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
36                        const TargetAsmInfo *T)
37 : FunctionNumber(0), O(o), TM(tm), TAI(T)
38 {}
39
40 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
41   return TAI->getTextSection();
42 }
43
44
45 /// SwitchToTextSection - Switch to the specified text section of the executable
46 /// if we are not already in it!
47 ///
48 void AsmPrinter::SwitchToTextSection(const char *NewSection,
49                                      const GlobalValue *GV) {
50   std::string NS;
51   if (GV && GV->hasSection())
52     NS = TAI->getSwitchToSectionDirective() + GV->getSection();
53   else
54     NS = NewSection;
55   
56   // If we're already in this section, we're done.
57   if (CurrentSection == NS) return;
58
59   // Close the current section, if applicable.
60   if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
61     O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
62
63   CurrentSection = NS;
64
65   if (!CurrentSection.empty())
66     O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
67 }
68
69 /// SwitchToDataSection - Switch to the specified data section of the executable
70 /// if we are not already in it!
71 ///
72 void AsmPrinter::SwitchToDataSection(const char *NewSection,
73                                      const GlobalValue *GV) {
74   std::string NS;
75   if (GV && GV->hasSection())
76     NS = TAI->getSwitchToSectionDirective() + GV->getSection();
77   else
78     NS = NewSection;
79   
80   // If we're already in this section, we're done.
81   if (CurrentSection == NS) return;
82
83   // Close the current section, if applicable.
84   if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
85     O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
86
87   CurrentSection = NS;
88   
89   if (!CurrentSection.empty())
90     O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
91 }
92
93
94 bool AsmPrinter::doInitialization(Module &M) {
95   Mang = new Mangler(M, TAI->getGlobalPrefix());
96   
97   if (!M.getModuleInlineAsm().empty())
98     O << TAI->getCommentString() << " Start of file scope inline assembly\n"
99       << M.getModuleInlineAsm()
100       << "\n" << TAI->getCommentString()
101       << " End of file scope inline assembly\n";
102
103   SwitchToDataSection("");   // Reset back to no section.
104   
105   if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
106     MMI->AnalyzeModule(M);
107   }
108   
109   return false;
110 }
111
112 bool AsmPrinter::doFinalization(Module &M) {
113   if (TAI->getWeakRefDirective()) {
114     if (ExtWeakSymbols.begin() != ExtWeakSymbols.end())
115       SwitchToDataSection("");
116
117     for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
118          e = ExtWeakSymbols.end(); i != e; ++i) {
119       const GlobalValue *GV = *i;
120       std::string Name = Mang->getValueName(GV);
121       O << TAI->getWeakRefDirective() << Name << "\n";
122     }
123   }
124
125   delete Mang; Mang = 0;
126   return false;
127 }
128
129 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
130   // What's my mangled name?
131   CurrentFnName = Mang->getValueName(MF.getFunction());
132   IncrementFunctionNumber();
133 }
134
135 /// EmitConstantPool - Print to the current output stream assembly
136 /// representations of the constants in the constant pool MCP. This is
137 /// used to print out constants which have been "spilled to memory" by
138 /// the code generator.
139 ///
140 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
141   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
142   if (CP.empty()) return;
143
144   // Some targets require 4-, 8-, and 16- byte constant literals to be placed
145   // in special sections.
146   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
147   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
148   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
149   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
150   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
151   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
152     MachineConstantPoolEntry CPE = CP[i];
153     const Type *Ty = CPE.getType();
154     if (TAI->getFourByteConstantSection() &&
155         TM.getTargetData()->getTypeSize(Ty) == 4)
156       FourByteCPs.push_back(std::make_pair(CPE, i));
157     else if (TAI->getEightByteConstantSection() &&
158              TM.getTargetData()->getTypeSize(Ty) == 8)
159       EightByteCPs.push_back(std::make_pair(CPE, i));
160     else if (TAI->getSixteenByteConstantSection() &&
161              TM.getTargetData()->getTypeSize(Ty) == 16)
162       SixteenByteCPs.push_back(std::make_pair(CPE, i));
163     else
164       OtherCPs.push_back(std::make_pair(CPE, i));
165   }
166
167   unsigned Alignment = MCP->getConstantPoolAlignment();
168   EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
169   EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
170   EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
171                    SixteenByteCPs);
172   EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
173 }
174
175 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
176                std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
177   if (CP.empty()) return;
178
179   SwitchToDataSection(Section);
180   EmitAlignment(Alignment);
181   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
182     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
183       << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
184     WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
185     if (CP[i].first.isMachineConstantPoolEntry())
186       EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
187      else
188       EmitGlobalConstant(CP[i].first.Val.ConstVal);
189     if (i != e-1) {
190       const Type *Ty = CP[i].first.getType();
191       unsigned EntSize =
192         TM.getTargetData()->getTypeSize(Ty);
193       unsigned ValEnd = CP[i].first.getOffset() + EntSize;
194       // Emit inter-object padding for alignment.
195       EmitZeros(CP[i+1].first.getOffset()-ValEnd);
196     }
197   }
198 }
199
200 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
201 /// by the current function to the current output stream.  
202 ///
203 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
204                                    MachineFunction &MF) {
205   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
206   if (JT.empty()) return;
207   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
208   
209   // Use JumpTableDirective otherwise honor the entry size from the jump table
210   // info.
211   const char *JTEntryDirective = TAI->getJumpTableDirective();
212   bool HadJTEntryDirective = JTEntryDirective != NULL;
213   if (!HadJTEntryDirective) {
214     JTEntryDirective = MJTI->getEntrySize() == 4 ?
215       TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
216   }
217   
218   // Pick the directive to use to print the jump table entries, and switch to 
219   // the appropriate section.
220   TargetLowering *LoweringInfo = TM.getTargetLowering();
221
222   const char* JumpTableDataSection = TAI->getJumpTableDataSection();  
223   if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
224      !JumpTableDataSection) {
225     // In PIC mode, we need to emit the jump table to the same section as the
226     // function body itself, otherwise the label differences won't make sense.
227     // We should also do if the section name is NULL.
228     const Function *F = MF.getFunction();
229     SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
230   } else {
231     SwitchToDataSection(JumpTableDataSection);
232   }
233   
234   EmitAlignment(Log2_32(MJTI->getAlignment()));
235   
236   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
237     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
238     
239     // If this jump table was deleted, ignore it. 
240     if (JTBBs.empty()) continue;
241
242     // For PIC codegen, if possible we want to use the SetDirective to reduce
243     // the number of relocations the assembler will generate for the jump table.
244     // Set directives are all printed before the jump table itself.
245     std::set<MachineBasicBlock*> EmittedSets;
246     if (TAI->getSetDirective() && IsPic)
247       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
248         if (EmittedSets.insert(JTBBs[ii]).second)
249           printSetLabel(i, JTBBs[ii]);
250     
251     // On some targets (e.g. darwin) we want to emit two consequtive labels
252     // before each jump table.  The first label is never referenced, but tells
253     // the assembler and linker the extents of the jump table object.  The
254     // second label is actually referenced by the code.
255     if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
256       O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
257     
258     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
259       << '_' << i << ":\n";
260     
261     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
262       O << JTEntryDirective << ' ';
263       // If we have emitted set directives for the jump table entries, print 
264       // them rather than the entries themselves.  If we're emitting PIC, then
265       // emit the table entries as differences between two text section labels.
266       // If we're emitting non-PIC code, then emit the entries as direct
267       // references to the target basic blocks.
268       if (!EmittedSets.empty()) {
269         O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
270           << '_' << i << "_set_" << JTBBs[ii]->getNumber();
271       } else if (IsPic) {
272         printBasicBlockLabel(JTBBs[ii], false, false);
273         // If the arch uses custom Jump Table directives, don't calc relative to
274         // JT
275         if (!HadJTEntryDirective) 
276           O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
277             << getFunctionNumber() << '_' << i;
278       } else {
279         printBasicBlockLabel(JTBBs[ii], false, false);
280       }
281       O << '\n';
282     }
283   }
284 }
285
286 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
287 /// special global used by LLVM.  If so, emit it and return true, otherwise
288 /// do nothing and return false.
289 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
290   // Ignore debug and non-emitted data.
291   if (GV->getSection() == "llvm.metadata") return true;
292   
293   if (!GV->hasAppendingLinkage()) return false;
294
295   assert(GV->hasInitializer() && "Not a special LLVM global!");
296   
297   if (GV->getName() == "llvm.used") {
298     if (TAI->getUsedDirective() != 0)    // No need to emit this at all.
299       EmitLLVMUsedList(GV->getInitializer());
300     return true;
301   }
302
303   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
304     SwitchToDataSection(TAI->getStaticCtorsSection());
305     EmitAlignment(2, 0);
306     EmitXXStructorList(GV->getInitializer());
307     return true;
308   } 
309   
310   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
311     SwitchToDataSection(TAI->getStaticDtorsSection());
312     EmitAlignment(2, 0);
313     EmitXXStructorList(GV->getInitializer());
314     return true;
315   }
316   
317   return false;
318 }
319
320 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
321 /// global in the specified llvm.used list as being used with this directive.
322 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
323   const char *Directive = TAI->getUsedDirective();
324
325   // Should be an array of 'sbyte*'.
326   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
327   if (InitList == 0) return;
328   
329   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
330     O << Directive;
331     EmitConstantValueOnly(InitList->getOperand(i));
332     O << "\n";
333   }
334 }
335
336 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
337 /// function pointers, ignoring the init priority.
338 void AsmPrinter::EmitXXStructorList(Constant *List) {
339   // Should be an array of '{ int, void ()* }' structs.  The first value is the
340   // init priority, which we ignore.
341   if (!isa<ConstantArray>(List)) return;
342   ConstantArray *InitList = cast<ConstantArray>(List);
343   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
344     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
345       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
346
347       if (CS->getOperand(1)->isNullValue())
348         return;  // Found a null terminator, exit printing.
349       // Emit the function pointer.
350       EmitGlobalConstant(CS->getOperand(1));
351     }
352 }
353
354 /// getGlobalLinkName - Returns the asm/link name of of the specified
355 /// global variable.  Should be overridden by each target asm printer to
356 /// generate the appropriate value.
357 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
358   std::string LinkName;
359   
360   if (isa<Function>(GV)) {
361     LinkName += TAI->getFunctionAddrPrefix();
362     LinkName += Mang->getValueName(GV);
363     LinkName += TAI->getFunctionAddrSuffix();
364   } else {
365     LinkName += TAI->getGlobalVarAddrPrefix();
366     LinkName += Mang->getValueName(GV);
367     LinkName += TAI->getGlobalVarAddrSuffix();
368   }  
369   
370   return LinkName;
371 }
372
373 /// EmitExternalGlobal - Emit the external reference to a global variable.
374 /// Should be overridden if an indirect reference should be used.
375 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
376   O << getGlobalLinkName(GV);
377 }
378
379
380
381 //===----------------------------------------------------------------------===//
382 /// LEB 128 number encoding.
383
384 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
385 /// representing an unsigned leb128 value.
386 void AsmPrinter::PrintULEB128(unsigned Value) const {
387   do {
388     unsigned Byte = Value & 0x7f;
389     Value >>= 7;
390     if (Value) Byte |= 0x80;
391     O << "0x" << std::hex << Byte << std::dec;
392     if (Value) O << ", ";
393   } while (Value);
394 }
395
396 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
397 /// value.
398 unsigned AsmPrinter::SizeULEB128(unsigned Value) {
399   unsigned Size = 0;
400   do {
401     Value >>= 7;
402     Size += sizeof(int8_t);
403   } while (Value);
404   return Size;
405 }
406
407 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
408 /// representing a signed leb128 value.
409 void AsmPrinter::PrintSLEB128(int Value) const {
410   int Sign = Value >> (8 * sizeof(Value) - 1);
411   bool IsMore;
412   
413   do {
414     unsigned Byte = Value & 0x7f;
415     Value >>= 7;
416     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
417     if (IsMore) Byte |= 0x80;
418     O << "0x" << std::hex << Byte << std::dec;
419     if (IsMore) O << ", ";
420   } while (IsMore);
421 }
422
423 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
424 /// value.
425 unsigned AsmPrinter::SizeSLEB128(int Value) {
426   unsigned Size = 0;
427   int Sign = Value >> (8 * sizeof(Value) - 1);
428   bool IsMore;
429   
430   do {
431     unsigned Byte = Value & 0x7f;
432     Value >>= 7;
433     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
434     Size += sizeof(int8_t);
435   } while (IsMore);
436   return Size;
437 }
438
439 //===--------------------------------------------------------------------===//
440 // Emission and print routines
441 //
442
443 /// PrintHex - Print a value as a hexidecimal value.
444 ///
445 void AsmPrinter::PrintHex(int Value) const { 
446   O << "0x" << std::hex << Value << std::dec;
447 }
448
449 /// EOL - Print a newline character to asm stream.  If a comment is present
450 /// then it will be printed first.  Comments should not contain '\n'.
451 void AsmPrinter::EOL() const {
452   O << "\n";
453 }
454 void AsmPrinter::EOL(const std::string &Comment) const {
455   if (AsmVerbose && !Comment.empty()) {
456     O << "\t"
457       << TAI->getCommentString()
458       << " "
459       << Comment;
460   }
461   O << "\n";
462 }
463
464 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
465 /// unsigned leb128 value.
466 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
467   if (TAI->hasLEB128()) {
468     O << "\t.uleb128\t"
469       << Value;
470   } else {
471     O << TAI->getData8bitsDirective();
472     PrintULEB128(Value);
473   }
474 }
475
476 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
477 /// signed leb128 value.
478 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
479   if (TAI->hasLEB128()) {
480     O << "\t.sleb128\t"
481       << Value;
482   } else {
483     O << TAI->getData8bitsDirective();
484     PrintSLEB128(Value);
485   }
486 }
487
488 /// EmitInt8 - Emit a byte directive and value.
489 ///
490 void AsmPrinter::EmitInt8(int Value) const {
491   O << TAI->getData8bitsDirective();
492   PrintHex(Value & 0xFF);
493 }
494
495 /// EmitInt16 - Emit a short directive and value.
496 ///
497 void AsmPrinter::EmitInt16(int Value) const {
498   O << TAI->getData16bitsDirective();
499   PrintHex(Value & 0xFFFF);
500 }
501
502 /// EmitInt32 - Emit a long directive and value.
503 ///
504 void AsmPrinter::EmitInt32(int Value) const {
505   O << TAI->getData32bitsDirective();
506   PrintHex(Value);
507 }
508
509 /// EmitInt64 - Emit a long long directive and value.
510 ///
511 void AsmPrinter::EmitInt64(uint64_t Value) const {
512   if (TAI->getData64bitsDirective()) {
513     O << TAI->getData64bitsDirective();
514     PrintHex(Value);
515   } else {
516     if (TM.getTargetData()->isBigEndian()) {
517       EmitInt32(unsigned(Value >> 32)); O << "\n";
518       EmitInt32(unsigned(Value));
519     } else {
520       EmitInt32(unsigned(Value)); O << "\n";
521       EmitInt32(unsigned(Value >> 32));
522     }
523   }
524 }
525
526 /// toOctal - Convert the low order bits of X into an octal digit.
527 ///
528 static inline char toOctal(int X) {
529   return (X&7)+'0';
530 }
531
532 /// printStringChar - Print a char, escaped if necessary.
533 ///
534 static void printStringChar(std::ostream &O, unsigned char C) {
535   if (C == '"') {
536     O << "\\\"";
537   } else if (C == '\\') {
538     O << "\\\\";
539   } else if (isprint(C)) {
540     O << C;
541   } else {
542     switch(C) {
543     case '\b': O << "\\b"; break;
544     case '\f': O << "\\f"; break;
545     case '\n': O << "\\n"; break;
546     case '\r': O << "\\r"; break;
547     case '\t': O << "\\t"; break;
548     default:
549       O << '\\';
550       O << toOctal(C >> 6);
551       O << toOctal(C >> 3);
552       O << toOctal(C >> 0);
553       break;
554     }
555   }
556 }
557
558 /// EmitString - Emit a string with quotes and a null terminator.
559 /// Special characters are emitted properly.
560 /// \literal (Eg. '\t') \endliteral
561 void AsmPrinter::EmitString(const std::string &String) const {
562   const char* AscizDirective = TAI->getAscizDirective();
563   if (AscizDirective)
564     O << AscizDirective;
565   else
566     O << TAI->getAsciiDirective();
567   O << "\"";
568   for (unsigned i = 0, N = String.size(); i < N; ++i) {
569     unsigned char C = String[i];
570     printStringChar(O, C);
571   }
572   if (AscizDirective)
573     O << "\"";
574   else
575     O << "\\0\"";
576 }
577
578
579 //===----------------------------------------------------------------------===//
580
581 // EmitAlignment - Emit an alignment directive to the specified power of two.
582 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
583   if (GV && GV->getAlignment())
584     NumBits = Log2_32(GV->getAlignment());
585   if (NumBits == 0) return;   // No need to emit alignment.
586   if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
587   O << TAI->getAlignDirective() << NumBits << "\n";
588 }
589
590     
591 /// EmitZeros - Emit a block of zeros.
592 ///
593 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
594   if (NumZeros) {
595     if (TAI->getZeroDirective()) {
596       O << TAI->getZeroDirective() << NumZeros;
597       if (TAI->getZeroDirectiveSuffix())
598         O << TAI->getZeroDirectiveSuffix();
599       O << "\n";
600     } else {
601       for (; NumZeros; --NumZeros)
602         O << TAI->getData8bitsDirective() << "0\n";
603     }
604   }
605 }
606
607 // Print out the specified constant, without a storage class.  Only the
608 // constants valid in constant expressions can occur here.
609 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
610   if (CV->isNullValue() || isa<UndefValue>(CV))
611     O << "0";
612   else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
613     O << CI->getZExtValue();
614   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
615     // This is a constant address for a global variable or function. Use the
616     // name of the variable or function as the address value, possibly
617     // decorating it with GlobalVarAddrPrefix/Suffix or
618     // FunctionAddrPrefix/Suffix (these all default to "" )
619     if (isa<Function>(GV)) {
620       O << TAI->getFunctionAddrPrefix()
621         << Mang->getValueName(GV)
622         << TAI->getFunctionAddrSuffix();
623     } else {
624       O << TAI->getGlobalVarAddrPrefix()
625         << Mang->getValueName(GV)
626         << TAI->getGlobalVarAddrSuffix();
627     }
628   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
629     const TargetData *TD = TM.getTargetData();
630     unsigned Opcode = CE->getOpcode();    
631     switch (Opcode) {
632     case Instruction::GetElementPtr: {
633       // generate a symbolic expression for the byte address
634       const Constant *ptrVal = CE->getOperand(0);
635       SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
636       if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
637                                                 idxVec.size())) {
638         if (Offset)
639           O << "(";
640         EmitConstantValueOnly(ptrVal);
641         if (Offset > 0)
642           O << ") + " << Offset;
643         else if (Offset < 0)
644           O << ") - " << -Offset;
645       } else {
646         EmitConstantValueOnly(ptrVal);
647       }
648       break;
649     }
650     case Instruction::Trunc:
651     case Instruction::ZExt:
652     case Instruction::SExt:
653     case Instruction::FPTrunc:
654     case Instruction::FPExt:
655     case Instruction::UIToFP:
656     case Instruction::SIToFP:
657     case Instruction::FPToUI:
658     case Instruction::FPToSI:
659       assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
660       break;
661     case Instruction::BitCast:
662       return EmitConstantValueOnly(CE->getOperand(0));
663
664     case Instruction::IntToPtr: {
665       // Handle casts to pointers by changing them into casts to the appropriate
666       // integer type.  This promotes constant folding and simplifies this code.
667       Constant *Op = CE->getOperand(0);
668       Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
669       return EmitConstantValueOnly(Op);
670     }
671       
672       
673     case Instruction::PtrToInt: {
674       // Support only foldable casts to/from pointers that can be eliminated by
675       // changing the pointer to the appropriately sized integer type.
676       Constant *Op = CE->getOperand(0);
677       const Type *Ty = CE->getType();
678
679       // We can emit the pointer value into this slot if the slot is an
680       // integer slot greater or equal to the size of the pointer.
681       if (Ty->isInteger() &&
682           TD->getTypeSize(Ty) >= TD->getTypeSize(Op->getType()))
683         return EmitConstantValueOnly(Op);
684       
685       assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
686       EmitConstantValueOnly(Op);
687       break;
688     }
689     case Instruction::Add:
690     case Instruction::Sub:
691       O << "(";
692       EmitConstantValueOnly(CE->getOperand(0));
693       O << (Opcode==Instruction::Add ? ") + (" : ") - (");
694       EmitConstantValueOnly(CE->getOperand(1));
695       O << ")";
696       break;
697     default:
698       assert(0 && "Unsupported operator!");
699     }
700   } else {
701     assert(0 && "Unknown constant value!");
702   }
703 }
704
705 /// printAsCString - Print the specified array as a C compatible string, only if
706 /// the predicate isString is true.
707 ///
708 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
709                            unsigned LastElt) {
710   assert(CVA->isString() && "Array is not string compatible!");
711
712   O << "\"";
713   for (unsigned i = 0; i != LastElt; ++i) {
714     unsigned char C =
715         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
716     printStringChar(O, C);
717   }
718   O << "\"";
719 }
720
721 /// EmitString - Emit a zero-byte-terminated string constant.
722 ///
723 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
724   unsigned NumElts = CVA->getNumOperands();
725   if (TAI->getAscizDirective() && NumElts && 
726       cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
727     O << TAI->getAscizDirective();
728     printAsCString(O, CVA, NumElts-1);
729   } else {
730     O << TAI->getAsciiDirective();
731     printAsCString(O, CVA, NumElts);
732   }
733   O << "\n";
734 }
735
736 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
737 ///
738 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
739   const TargetData *TD = TM.getTargetData();
740
741   if (CV->isNullValue() || isa<UndefValue>(CV)) {
742     EmitZeros(TD->getTypeSize(CV->getType()));
743     return;
744   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
745     if (CVA->isString()) {
746       EmitString(CVA);
747     } else { // Not a string.  Print the values in successive locations
748       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
749         EmitGlobalConstant(CVA->getOperand(i));
750     }
751     return;
752   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
753     // Print the fields in successive locations. Pad to align if needed!
754     const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
755     uint64_t sizeSoFar = 0;
756     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
757       const Constant* field = CVS->getOperand(i);
758
759       // Check if padding is needed and insert one or more 0s.
760       uint64_t fieldSize = TD->getTypeSize(field->getType());
761       uint64_t padSize = ((i == e-1? cvsLayout->getSizeInBytes()
762                            : cvsLayout->getElementOffset(i+1))
763                           - cvsLayout->getElementOffset(i)) - fieldSize;
764       sizeSoFar += fieldSize + padSize;
765
766       // Now print the actual field value
767       EmitGlobalConstant(field);
768
769       // Insert the field padding unless it's zero bytes...
770       EmitZeros(padSize);
771     }
772     assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
773            "Layout of constant struct may be incorrect!");
774     return;
775   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
776     // FP Constants are printed as integer constants to avoid losing
777     // precision...
778     double Val = CFP->getValue();
779     if (CFP->getType() == Type::DoubleTy) {
780       if (TAI->getData64bitsDirective())
781         O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
782           << TAI->getCommentString() << " double value: " << Val << "\n";
783       else if (TD->isBigEndian()) {
784         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
785           << "\t" << TAI->getCommentString()
786           << " double most significant word " << Val << "\n";
787         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
788           << "\t" << TAI->getCommentString()
789           << " double least significant word " << Val << "\n";
790       } else {
791         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
792           << "\t" << TAI->getCommentString()
793           << " double least significant word " << Val << "\n";
794         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
795           << "\t" << TAI->getCommentString()
796           << " double most significant word " << Val << "\n";
797       }
798       return;
799     } else {
800       O << TAI->getData32bitsDirective() << FloatToBits(Val)
801         << "\t" << TAI->getCommentString() << " float " << Val << "\n";
802       return;
803     }
804   } else if (CV->getType() == Type::Int64Ty) {
805     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
806       uint64_t Val = CI->getZExtValue();
807
808       if (TAI->getData64bitsDirective())
809         O << TAI->getData64bitsDirective() << Val << "\n";
810       else if (TD->isBigEndian()) {
811         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
812           << "\t" << TAI->getCommentString()
813           << " Double-word most significant word " << Val << "\n";
814         O << TAI->getData32bitsDirective() << unsigned(Val)
815           << "\t" << TAI->getCommentString()
816           << " Double-word least significant word " << Val << "\n";
817       } else {
818         O << TAI->getData32bitsDirective() << unsigned(Val)
819           << "\t" << TAI->getCommentString()
820           << " Double-word least significant word " << Val << "\n";
821         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
822           << "\t" << TAI->getCommentString()
823           << " Double-word most significant word " << Val << "\n";
824       }
825       return;
826     }
827   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
828     const VectorType *PTy = CP->getType();
829     
830     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
831       EmitGlobalConstant(CP->getOperand(I));
832     
833     return;
834   }
835
836   const Type *type = CV->getType();
837   printDataDirective(type);
838   EmitConstantValueOnly(CV);
839   O << "\n";
840 }
841
842 void
843 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
844   // Target doesn't support this yet!
845   abort();
846 }
847
848 /// PrintSpecial - Print information related to the specified machine instr
849 /// that is independent of the operand, and may be independent of the instr
850 /// itself.  This can be useful for portably encoding the comment character
851 /// or other bits of target-specific knowledge into the asmstrings.  The
852 /// syntax used is ${:comment}.  Targets can override this to add support
853 /// for their own strange codes.
854 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
855   if (!strcmp(Code, "private")) {
856     O << TAI->getPrivateGlobalPrefix();
857   } else if (!strcmp(Code, "comment")) {
858     O << TAI->getCommentString();
859   } else if (!strcmp(Code, "uid")) {
860     // Assign a unique ID to this machine instruction.
861     static const MachineInstr *LastMI = 0;
862     static const Function *F = 0;
863     static unsigned Counter = 0U-1;
864
865     // Comparing the address of MI isn't sufficient, because machineinstrs may
866     // be allocated to the same address across functions.
867     const Function *ThisF = MI->getParent()->getParent()->getFunction();
868     
869     // If this is a new machine instruction, bump the counter.
870     if (LastMI != MI || F != ThisF) {
871       ++Counter;
872       LastMI = MI;
873       F = ThisF;
874     }
875     O << Counter;
876   } else {
877     cerr << "Unknown special formatter '" << Code
878          << "' for machine instr: " << *MI;
879     exit(1);
880   }    
881 }
882
883
884 /// printInlineAsm - This method formats and prints the specified machine
885 /// instruction that is an inline asm.
886 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
887   unsigned NumOperands = MI->getNumOperands();
888   
889   // Count the number of register definitions.
890   unsigned NumDefs = 0;
891   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
892        ++NumDefs)
893     assert(NumDefs != NumOperands-1 && "No asm string?");
894   
895   assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
896
897   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
898   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
899
900   // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
901   if (AsmStr[0] == 0) {
902     O << "\n";  // Tab already printed, avoid double indenting next instr.
903     return;
904   }
905   
906   O << TAI->getInlineAsmStart() << "\n\t";
907
908   // The variant of the current asmprinter.
909   int AsmPrinterVariant = TAI->getAssemblerDialect();
910
911   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
912   const char *LastEmitted = AsmStr; // One past the last character emitted.
913   
914   while (*LastEmitted) {
915     switch (*LastEmitted) {
916     default: {
917       // Not a special case, emit the string section literally.
918       const char *LiteralEnd = LastEmitted+1;
919       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
920              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
921         ++LiteralEnd;
922       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
923         O.write(LastEmitted, LiteralEnd-LastEmitted);
924       LastEmitted = LiteralEnd;
925       break;
926     }
927     case '\n':
928       ++LastEmitted;   // Consume newline character.
929       O << "\n\t";     // Indent code with newline.
930       break;
931     case '$': {
932       ++LastEmitted;   // Consume '$' character.
933       bool Done = true;
934
935       // Handle escapes.
936       switch (*LastEmitted) {
937       default: Done = false; break;
938       case '$':     // $$ -> $
939         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
940           O << '$';
941         ++LastEmitted;  // Consume second '$' character.
942         break;
943       case '(':             // $( -> same as GCC's { character.
944         ++LastEmitted;      // Consume '(' character.
945         if (CurVariant != -1) {
946           cerr << "Nested variants found in inline asm string: '"
947                << AsmStr << "'\n";
948           exit(1);
949         }
950         CurVariant = 0;     // We're in the first variant now.
951         break;
952       case '|':
953         ++LastEmitted;  // consume '|' character.
954         if (CurVariant == -1) {
955           cerr << "Found '|' character outside of variant in inline asm "
956                << "string: '" << AsmStr << "'\n";
957           exit(1);
958         }
959         ++CurVariant;   // We're in the next variant.
960         break;
961       case ')':         // $) -> same as GCC's } char.
962         ++LastEmitted;  // consume ')' character.
963         if (CurVariant == -1) {
964           cerr << "Found '}' character outside of variant in inline asm "
965                << "string: '" << AsmStr << "'\n";
966           exit(1);
967         }
968         CurVariant = -1;
969         break;
970       }
971       if (Done) break;
972       
973       bool HasCurlyBraces = false;
974       if (*LastEmitted == '{') {     // ${variable}
975         ++LastEmitted;               // Consume '{' character.
976         HasCurlyBraces = true;
977       }
978       
979       const char *IDStart = LastEmitted;
980       char *IDEnd;
981       errno = 0;
982       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
983       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
984         cerr << "Bad $ operand number in inline asm string: '" 
985              << AsmStr << "'\n";
986         exit(1);
987       }
988       LastEmitted = IDEnd;
989       
990       char Modifier[2] = { 0, 0 };
991       
992       if (HasCurlyBraces) {
993         // If we have curly braces, check for a modifier character.  This
994         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
995         if (*LastEmitted == ':') {
996           ++LastEmitted;    // Consume ':' character.
997           if (*LastEmitted == 0) {
998             cerr << "Bad ${:} expression in inline asm string: '" 
999                  << AsmStr << "'\n";
1000             exit(1);
1001           }
1002           
1003           Modifier[0] = *LastEmitted;
1004           ++LastEmitted;    // Consume modifier character.
1005         }
1006         
1007         if (*LastEmitted != '}') {
1008           cerr << "Bad ${} expression in inline asm string: '" 
1009                << AsmStr << "'\n";
1010           exit(1);
1011         }
1012         ++LastEmitted;    // Consume '}' character.
1013       }
1014       
1015       if ((unsigned)Val >= NumOperands-1) {
1016         cerr << "Invalid $ operand number in inline asm string: '" 
1017              << AsmStr << "'\n";
1018         exit(1);
1019       }
1020       
1021       // Okay, we finally have a value number.  Ask the target to print this
1022       // operand!
1023       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1024         unsigned OpNo = 1;
1025
1026         bool Error = false;
1027
1028         // Scan to find the machine operand number for the operand.
1029         for (; Val; --Val) {
1030           if (OpNo >= MI->getNumOperands()) break;
1031           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1032           OpNo += (OpFlags >> 3) + 1;
1033         }
1034
1035         if (OpNo >= MI->getNumOperands()) {
1036           Error = true;
1037         } else {
1038           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1039           ++OpNo;  // Skip over the ID number.
1040
1041           AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1042           if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1043             Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1044                                               Modifier[0] ? Modifier : 0);
1045           } else {
1046             Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1047                                         Modifier[0] ? Modifier : 0);
1048           }
1049         }
1050         if (Error) {
1051           cerr << "Invalid operand found in inline asm: '"
1052                << AsmStr << "'\n";
1053           MI->dump();
1054           exit(1);
1055         }
1056       }
1057       break;
1058     }
1059     }
1060   }
1061   O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1062 }
1063
1064 /// printLabel - This method prints a local label used by debug and
1065 /// exception handling tables.
1066 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1067   O << "\n"
1068     << TAI->getPrivateGlobalPrefix()
1069     << "label"
1070     << MI->getOperand(0).getImmedValue()
1071     << ":\n";
1072 }
1073
1074 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1075 /// instruction, using the specified assembler variant.  Targets should
1076 /// overried this to format as appropriate.
1077 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1078                                  unsigned AsmVariant, const char *ExtraCode) {
1079   // Target doesn't support this yet!
1080   return true;
1081 }
1082
1083 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1084                                        unsigned AsmVariant,
1085                                        const char *ExtraCode) {
1086   // Target doesn't support this yet!
1087   return true;
1088 }
1089
1090 /// printBasicBlockLabel - This method prints the label for the specified
1091 /// MachineBasicBlock
1092 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1093                                       bool printColon,
1094                                       bool printComment) const {
1095   O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
1096     << MBB->getNumber();
1097   if (printColon)
1098     O << ':';
1099   if (printComment && MBB->getBasicBlock())
1100     O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
1101 }
1102
1103 /// printSetLabel - This method prints a set label for the specified
1104 /// MachineBasicBlock
1105 void AsmPrinter::printSetLabel(unsigned uid, 
1106                                const MachineBasicBlock *MBB) const {
1107   if (!TAI->getSetDirective())
1108     return;
1109   
1110   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1111     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1112   printBasicBlockLabel(MBB, false, false);
1113   O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
1114     << '_' << uid << '\n';
1115 }
1116
1117 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
1118                                const MachineBasicBlock *MBB) const {
1119   if (!TAI->getSetDirective())
1120     return;
1121   
1122   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1123     << getFunctionNumber() << '_' << uid << '_' << uid2
1124     << "_set_" << MBB->getNumber() << ',';
1125   printBasicBlockLabel(MBB, false, false);
1126   O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
1127     << '_' << uid << '_' << uid2 << '\n';
1128 }
1129
1130 /// printDataDirective - This method prints the asm directive for the
1131 /// specified type.
1132 void AsmPrinter::printDataDirective(const Type *type) {
1133   const TargetData *TD = TM.getTargetData();
1134   switch (type->getTypeID()) {
1135   case Type::IntegerTyID: {
1136     unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1137     if (BitWidth <= 8)
1138       O << TAI->getData8bitsDirective();
1139     else if (BitWidth <= 16)
1140       O << TAI->getData16bitsDirective();
1141     else if (BitWidth <= 32)
1142       O << TAI->getData32bitsDirective();
1143     else if (BitWidth <= 64) {
1144       assert(TAI->getData64bitsDirective() &&
1145              "Target cannot handle 64-bit constant exprs!");
1146       O << TAI->getData64bitsDirective();
1147     }
1148     break;
1149   }
1150   case Type::PointerTyID:
1151     if (TD->getPointerSize() == 8) {
1152       assert(TAI->getData64bitsDirective() &&
1153              "Target cannot handle 64-bit pointer exprs!");
1154       O << TAI->getData64bitsDirective();
1155     } else {
1156       O << TAI->getData32bitsDirective();
1157     }
1158     break;
1159   case Type::FloatTyID: case Type::DoubleTyID:
1160     assert (0 && "Should have already output floating point constant.");
1161   default:
1162     assert (0 && "Can't handle printing this type of thing");
1163     break;
1164   }
1165 }
1166