Missed pieces for ARM HardFP ABI.
[oota-llvm.git] / lib / Target / ARM / AsmPrinter / ARMAsmPrinter.cpp
1 //===-- ARMAsmPrinter.cpp - ARM LLVM assembly writer ----------------------===//
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 contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format ARM assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "ARM.h"
17 #include "ARMBuildAttrs.h"
18 #include "ARMTargetMachine.h"
19 #include "ARMAddressingModes.h"
20 #include "ARMConstantPoolValue.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Module.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/DwarfWriter.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/StringSet.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include <cctype>
45 using namespace llvm;
46
47 STATISTIC(EmittedInsts, "Number of machine instrs printed");
48
49 namespace {
50   class VISIBILITY_HIDDEN ARMAsmPrinter : public AsmPrinter {
51     DwarfWriter *DW;
52
53     /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
54     /// make the right decision when printing asm code for different targets.
55     const ARMSubtarget *Subtarget;
56
57     /// AFI - Keep a pointer to ARMFunctionInfo for the current
58     /// MachineFunction.
59     ARMFunctionInfo *AFI;
60
61     /// MCP - Keep a pointer to constantpool entries of the current
62     /// MachineFunction.
63     const MachineConstantPool *MCP;
64
65     /// We name each basic block in a Function with a unique number, so
66     /// that we can consistently refer to them later. This is cleared
67     /// at the beginning of each call to runOnMachineFunction().
68     ///
69     typedef std::map<const Value *, unsigned> ValueMapTy;
70     ValueMapTy NumberForBB;
71
72     /// GVNonLazyPtrs - Keeps the set of GlobalValues that require
73     /// non-lazy-pointers for indirect access.
74     StringMap<std::string> GVNonLazyPtrs;
75
76     /// HiddenGVNonLazyPtrs - Keeps the set of GlobalValues with hidden
77     /// visibility that require non-lazy-pointers for indirect access.
78     StringMap<std::string> HiddenGVNonLazyPtrs;
79
80     struct FnStubInfo {
81       std::string Stub, LazyPtr, SLP, SCV;
82       
83       FnStubInfo() {}
84       
85       void Init(const GlobalValue *GV, Mangler *Mang) {
86         // Already initialized.
87         if (!Stub.empty()) return;
88         Stub = Mang->getMangledName(GV, "$stub", true);
89         LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
90         SLP = Mang->getMangledName(GV, "$slp", true);
91         SCV = Mang->getMangledName(GV, "$scv", true);
92       }
93       
94       void Init(const std::string &GV, Mangler *Mang) {
95         // Already initialized.
96         if (!Stub.empty()) return;
97         Stub = Mang->makeNameProper(GV + "$stub", Mangler::Private);
98         LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr", Mangler::Private);
99         SLP = Mang->makeNameProper(GV + "$slp", Mangler::Private);
100         SCV = Mang->makeNameProper(GV + "$scv", Mangler::Private);
101       }
102     };
103     
104     /// FnStubs - Keeps the set of external function GlobalAddresses that the
105     /// asm printer should generate stubs for.
106     StringMap<FnStubInfo> FnStubs;
107
108     /// True if asm printer is printing a series of CONSTPOOL_ENTRY.
109     bool InCPMode;
110   public:
111     explicit ARMAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
112                            const TargetAsmInfo *T, bool V)
113       : AsmPrinter(O, TM, T, V), DW(0), AFI(NULL), MCP(NULL),
114         InCPMode(false) {
115       Subtarget = &TM.getSubtarget<ARMSubtarget>();
116     }
117
118     virtual const char *getPassName() const {
119       return "ARM Assembly Printer";
120     }
121
122     void printOperand(const MachineInstr *MI, int OpNum,
123                       const char *Modifier = 0);
124     void printSOImmOperand(const MachineInstr *MI, int OpNum);
125     void printSOImm2PartOperand(const MachineInstr *MI, int OpNum);
126     void printSORegOperand(const MachineInstr *MI, int OpNum);
127     void printAddrMode2Operand(const MachineInstr *MI, int OpNum);
128     void printAddrMode2OffsetOperand(const MachineInstr *MI, int OpNum);
129     void printAddrMode3Operand(const MachineInstr *MI, int OpNum);
130     void printAddrMode3OffsetOperand(const MachineInstr *MI, int OpNum);
131     void printAddrMode4Operand(const MachineInstr *MI, int OpNum,
132                                const char *Modifier = 0);
133     void printAddrMode5Operand(const MachineInstr *MI, int OpNum,
134                                const char *Modifier = 0);
135     void printAddrMode6Operand(const MachineInstr *MI, int OpNum);
136     void printAddrModePCOperand(const MachineInstr *MI, int OpNum,
137                                 const char *Modifier = 0);
138     void printBitfieldInvMaskImmOperand (const MachineInstr *MI, int OpNum);
139
140     void printThumbITMask(const MachineInstr *MI, int OpNum);
141     void printThumbAddrModeRROperand(const MachineInstr *MI, int OpNum);
142     void printThumbAddrModeRI5Operand(const MachineInstr *MI, int OpNum,
143                                       unsigned Scale);
144     void printThumbAddrModeS1Operand(const MachineInstr *MI, int OpNum);
145     void printThumbAddrModeS2Operand(const MachineInstr *MI, int OpNum);
146     void printThumbAddrModeS4Operand(const MachineInstr *MI, int OpNum);
147     void printThumbAddrModeSPOperand(const MachineInstr *MI, int OpNum);
148
149     void printT2SOOperand(const MachineInstr *MI, int OpNum);
150     void printT2AddrModeImm12Operand(const MachineInstr *MI, int OpNum);
151     void printT2AddrModeImm8Operand(const MachineInstr *MI, int OpNum);
152     void printT2AddrModeImm8s4Operand(const MachineInstr *MI, int OpNum);
153     void printT2AddrModeImm8OffsetOperand(const MachineInstr *MI, int OpNum);
154     void printT2AddrModeSoRegOperand(const MachineInstr *MI, int OpNum);
155
156     void printPredicateOperand(const MachineInstr *MI, int OpNum);
157     void printSBitModifierOperand(const MachineInstr *MI, int OpNum);
158     void printPCLabel(const MachineInstr *MI, int OpNum);
159     void printRegisterList(const MachineInstr *MI, int OpNum);
160     void printCPInstOperand(const MachineInstr *MI, int OpNum,
161                             const char *Modifier);
162     void printJTBlockOperand(const MachineInstr *MI, int OpNum);
163     void printJT2BlockOperand(const MachineInstr *MI, int OpNum);
164     void printTBAddrMode(const MachineInstr *MI, int OpNum);
165
166     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
167                                  unsigned AsmVariant, const char *ExtraCode);
168     virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
169                                        unsigned AsmVariant,
170                                        const char *ExtraCode);
171
172     void PrintGlobalVariable(const GlobalVariable* GVar);
173     bool printInstruction(const MachineInstr *MI);  // autogenerated.
174     void printMachineInstruction(const MachineInstr *MI);
175     bool runOnMachineFunction(MachineFunction &F);
176     bool doInitialization(Module &M);
177     bool doFinalization(Module &M);
178
179     /// EmitMachineConstantPoolValue - Print a machine constantpool value to
180     /// the .s file.
181     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
182       printDataDirective(MCPV->getType());
183
184       ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
185       GlobalValue *GV = ACPV->getGV();
186       std::string Name;
187       
188       
189       if (ACPV->isNonLazyPointer()) {
190         std::string SymName = Mang->getMangledName(GV);
191         Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
192         
193         if (GV->hasHiddenVisibility())
194           HiddenGVNonLazyPtrs[SymName] = Name;
195         else
196           GVNonLazyPtrs[SymName] = Name;
197       } else if (ACPV->isStub()) {
198         if (GV) {
199           FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
200           FnInfo.Init(GV, Mang);
201           Name = FnInfo.Stub;
202         } else {
203           FnStubInfo &FnInfo = FnStubs[Mang->makeNameProper(ACPV->getSymbol())];
204           FnInfo.Init(ACPV->getSymbol(), Mang);
205           Name = FnInfo.Stub;
206         }
207       } else {
208         if (GV)
209           Name = Mang->getMangledName(GV);
210         else
211           Name = Mang->makeNameProper(ACPV->getSymbol());
212       }
213       O << Name;
214       
215       
216       
217       if (ACPV->hasModifier()) O << "(" << ACPV->getModifier() << ")";
218       if (ACPV->getPCAdjustment() != 0) {
219         O << "-(" << TAI->getPrivateGlobalPrefix() << "PC"
220           << ACPV->getLabelId()
221           << "+" << (unsigned)ACPV->getPCAdjustment();
222          if (ACPV->mustAddCurrentAddress())
223            O << "-.";
224          O << ")";
225       }
226       O << "\n";
227     }
228     
229     void getAnalysisUsage(AnalysisUsage &AU) const {
230       AsmPrinter::getAnalysisUsage(AU);
231       AU.setPreservesAll();
232       AU.addRequired<MachineModuleInfo>();
233       AU.addRequired<DwarfWriter>();
234     }
235   };
236 } // end of anonymous namespace
237
238 #include "ARMGenAsmWriter.inc"
239
240 /// runOnMachineFunction - This uses the printInstruction()
241 /// method to print assembly for each instruction.
242 ///
243 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
244   this->MF = &MF;
245
246   AFI = MF.getInfo<ARMFunctionInfo>();
247   MCP = MF.getConstantPool();
248
249   SetupMachineFunction(MF);
250   O << "\n";
251
252   // NOTE: we don't print out constant pools here, they are handled as
253   // instructions.
254
255   O << '\n';
256   
257   // Print out labels for the function.
258   const Function *F = MF.getFunction();
259   SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
260
261   switch (F->getLinkage()) {
262   default: llvm_unreachable("Unknown linkage type!");
263   case Function::PrivateLinkage:
264   case Function::LinkerPrivateLinkage:
265   case Function::InternalLinkage:
266     break;
267   case Function::ExternalLinkage:
268     O << "\t.globl\t" << CurrentFnName << "\n";
269     break;
270   case Function::WeakAnyLinkage:
271   case Function::WeakODRLinkage:
272   case Function::LinkOnceAnyLinkage:
273   case Function::LinkOnceODRLinkage:
274     if (Subtarget->isTargetDarwin()) {
275       O << "\t.globl\t" << CurrentFnName << "\n";
276       O << "\t.weak_definition\t" << CurrentFnName << "\n";
277     } else {
278       O << TAI->getWeakRefDirective() << CurrentFnName << "\n";
279     }
280     break;
281   }
282
283   printVisibility(CurrentFnName, F->getVisibility());
284
285   if (AFI->isThumbFunction()) {
286     EmitAlignment(MF.getAlignment(), F, AFI->getAlign());
287     O << "\t.code\t16\n";
288     O << "\t.thumb_func";
289     if (Subtarget->isTargetDarwin())
290       O << "\t" << CurrentFnName;
291     O << "\n";
292     InCPMode = false;
293   } else {
294     EmitAlignment(MF.getAlignment(), F);
295   }
296
297   O << CurrentFnName << ":\n";
298   // Emit pre-function debug information.
299   DW->BeginFunction(&MF);
300
301   if (Subtarget->isTargetDarwin()) {
302     // If the function is empty, then we need to emit *something*. Otherwise,
303     // the function's label might be associated with something that it wasn't
304     // meant to be associated with. We emit a noop in this situation.
305     MachineFunction::iterator I = MF.begin();
306
307     if (++I == MF.end() && MF.front().empty())
308       O << "\tnop\n";
309   }
310
311   // Print out code for the function.
312   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
313        I != E; ++I) {
314     // Print a label for the basic block.
315     if (I != MF.begin()) {
316       printBasicBlockLabel(I, true, true, VerboseAsm);
317       O << '\n';
318     }
319     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
320          II != E; ++II) {
321       // Print the assembly for the instruction.
322       printMachineInstruction(II);
323     }
324   }
325
326   if (TAI->hasDotTypeDotSizeDirective())
327     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
328
329   // Emit post-function debug information.
330   DW->EndFunction(&MF);
331
332   return false;
333 }
334
335 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
336                                  const char *Modifier) {
337   const MachineOperand &MO = MI->getOperand(OpNum);
338   switch (MO.getType()) {
339   case MachineOperand::MO_Register: {
340     unsigned Reg = MO.getReg();
341     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
342       if (Modifier && strcmp(Modifier, "dregpair") == 0) {
343         unsigned DRegLo = TRI->getSubReg(Reg, 5); // arm_dsubreg_0
344         unsigned DRegHi = TRI->getSubReg(Reg, 6); // arm_dsubreg_1
345         O << '{'
346           << TRI->getAsmName(DRegLo) << ',' << TRI->getAsmName(DRegHi)
347           << '}';
348       } else {
349         O << TRI->getAsmName(Reg);
350       }
351     } else
352       llvm_unreachable("not implemented");
353     break;
354   }
355   case MachineOperand::MO_Immediate: {
356     if (!Modifier || strcmp(Modifier, "no_hash") != 0)
357       O << "#";
358
359     O << MO.getImm();
360     break;
361   }
362   case MachineOperand::MO_MachineBasicBlock:
363     printBasicBlockLabel(MO.getMBB());
364     return;
365   case MachineOperand::MO_GlobalAddress: {
366     bool isCallOp = Modifier && !strcmp(Modifier, "call");
367     GlobalValue *GV = MO.getGlobal();
368     std::string Name;
369     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
370     if (isExt && isCallOp && Subtarget->isTargetDarwin() &&
371         TM.getRelocationModel() != Reloc::Static) {
372       FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
373       FnInfo.Init(GV, Mang);
374       Name = FnInfo.Stub;
375     } else {
376       Name = Mang->getMangledName(GV);
377     }
378     
379     O << Name;
380
381     printOffset(MO.getOffset());
382
383     if (isCallOp && Subtarget->isTargetELF() &&
384         TM.getRelocationModel() == Reloc::PIC_)
385       O << "(PLT)";
386     break;
387   }
388   case MachineOperand::MO_ExternalSymbol: {
389     bool isCallOp = Modifier && !strcmp(Modifier, "call");
390     std::string Name;
391     if (isCallOp && Subtarget->isTargetDarwin() &&
392         TM.getRelocationModel() != Reloc::Static) {
393       FnStubInfo &FnInfo = FnStubs[Mang->makeNameProper(MO.getSymbolName())];
394       FnInfo.Init(MO.getSymbolName(), Mang);
395       Name = FnInfo.Stub;
396     } else
397       Name = Mang->makeNameProper(MO.getSymbolName());
398     
399     O << Name;
400     if (isCallOp && Subtarget->isTargetELF() &&
401         TM.getRelocationModel() == Reloc::PIC_)
402       O << "(PLT)";
403     break;
404   }
405   case MachineOperand::MO_ConstantPoolIndex:
406     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
407       << '_' << MO.getIndex();
408     break;
409   case MachineOperand::MO_JumpTableIndex:
410     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
411       << '_' << MO.getIndex();
412     break;
413   default:
414     O << "<unknown operand type>"; abort (); break;
415   }
416 }
417
418 static void printSOImm(formatted_raw_ostream &O, int64_t V, bool VerboseAsm,
419                        const TargetAsmInfo *TAI) {
420   // Break it up into two parts that make up a shifter immediate.
421   V = ARM_AM::getSOImmVal(V);
422   assert(V != -1 && "Not a valid so_imm value!");
423
424   unsigned Imm = ARM_AM::getSOImmValImm(V);
425   unsigned Rot = ARM_AM::getSOImmValRot(V);
426
427   // Print low-level immediate formation info, per
428   // A5.1.3: "Data-processing operands - Immediate".
429   if (Rot) {
430     O << "#" << Imm << ", " << Rot;
431     // Pretty printed version.
432     if (VerboseAsm)
433       O << ' ' << TAI->getCommentString()
434         << ' ' << (int)ARM_AM::rotr32(Imm, Rot);
435   } else {
436     O << "#" << Imm;
437   }
438 }
439
440 /// printSOImmOperand - SOImm is 4-bit rotate amount in bits 8-11 with 8-bit
441 /// immediate in bits 0-7.
442 void ARMAsmPrinter::printSOImmOperand(const MachineInstr *MI, int OpNum) {
443   const MachineOperand &MO = MI->getOperand(OpNum);
444   assert(MO.isImm() && "Not a valid so_imm value!");
445   printSOImm(O, MO.getImm(), VerboseAsm, TAI);
446 }
447
448 /// printSOImm2PartOperand - SOImm is broken into two pieces using a 'mov'
449 /// followed by an 'orr' to materialize.
450 void ARMAsmPrinter::printSOImm2PartOperand(const MachineInstr *MI, int OpNum) {
451   const MachineOperand &MO = MI->getOperand(OpNum);
452   assert(MO.isImm() && "Not a valid so_imm value!");
453   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO.getImm());
454   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO.getImm());
455   printSOImm(O, V1, VerboseAsm, TAI);
456   O << "\n\torr";
457   printPredicateOperand(MI, 2);
458   O << " ";
459   printOperand(MI, 0); 
460   O << ", ";
461   printOperand(MI, 0); 
462   O << ", ";
463   printSOImm(O, V2, VerboseAsm, TAI);
464 }
465
466 // so_reg is a 4-operand unit corresponding to register forms of the A5.1
467 // "Addressing Mode 1 - Data-processing operands" forms.  This includes:
468 //    REG 0   0           - e.g. R5
469 //    REG REG 0,SH_OPC    - e.g. R5, ROR R3
470 //    REG 0   IMM,SH_OPC  - e.g. R5, LSL #3
471 void ARMAsmPrinter::printSORegOperand(const MachineInstr *MI, int Op) {
472   const MachineOperand &MO1 = MI->getOperand(Op);
473   const MachineOperand &MO2 = MI->getOperand(Op+1);
474   const MachineOperand &MO3 = MI->getOperand(Op+2);
475
476   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
477   O << TRI->getAsmName(MO1.getReg());
478
479   // Print the shift opc.
480   O << ", "
481     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO3.getImm()))
482     << " ";
483
484   if (MO2.getReg()) {
485     assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
486     O << TRI->getAsmName(MO2.getReg());
487     assert(ARM_AM::getSORegOffset(MO3.getImm()) == 0);
488   } else {
489     O << "#" << ARM_AM::getSORegOffset(MO3.getImm());
490   }
491 }
492
493 void ARMAsmPrinter::printAddrMode2Operand(const MachineInstr *MI, int Op) {
494   const MachineOperand &MO1 = MI->getOperand(Op);
495   const MachineOperand &MO2 = MI->getOperand(Op+1);
496   const MachineOperand &MO3 = MI->getOperand(Op+2);
497
498   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
499     printOperand(MI, Op);
500     return;
501   }
502
503   O << "[" << TRI->getAsmName(MO1.getReg());
504
505   if (!MO2.getReg()) {
506     if (ARM_AM::getAM2Offset(MO3.getImm()))  // Don't print +0.
507       O << ", #"
508         << (char)ARM_AM::getAM2Op(MO3.getImm())
509         << ARM_AM::getAM2Offset(MO3.getImm());
510     O << "]";
511     return;
512   }
513
514   O << ", "
515     << (char)ARM_AM::getAM2Op(MO3.getImm())
516     << TRI->getAsmName(MO2.getReg());
517   
518   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm()))
519     O << ", "
520       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO3.getImm()))
521       << " #" << ShImm;
522   O << "]";
523 }
524
525 void ARMAsmPrinter::printAddrMode2OffsetOperand(const MachineInstr *MI, int Op){
526   const MachineOperand &MO1 = MI->getOperand(Op);
527   const MachineOperand &MO2 = MI->getOperand(Op+1);
528
529   if (!MO1.getReg()) {
530     unsigned ImmOffs = ARM_AM::getAM2Offset(MO2.getImm());
531     assert(ImmOffs && "Malformed indexed load / store!");
532     O << "#"
533       << (char)ARM_AM::getAM2Op(MO2.getImm())
534       << ImmOffs;
535     return;
536   }
537
538   O << (char)ARM_AM::getAM2Op(MO2.getImm())
539     << TRI->getAsmName(MO1.getReg());
540   
541   if (unsigned ShImm = ARM_AM::getAM2Offset(MO2.getImm()))
542     O << ", "
543       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO2.getImm()))
544       << " #" << ShImm;
545 }
546
547 void ARMAsmPrinter::printAddrMode3Operand(const MachineInstr *MI, int Op) {
548   const MachineOperand &MO1 = MI->getOperand(Op);
549   const MachineOperand &MO2 = MI->getOperand(Op+1);
550   const MachineOperand &MO3 = MI->getOperand(Op+2);
551   
552   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
553   O << "[" << TRI->getAsmName(MO1.getReg());
554
555   if (MO2.getReg()) {
556     O << ", "
557       << (char)ARM_AM::getAM3Op(MO3.getImm())
558       << TRI->getAsmName(MO2.getReg())
559       << "]";
560     return;
561   }
562   
563   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm()))
564     O << ", #"
565       << (char)ARM_AM::getAM3Op(MO3.getImm())
566       << ImmOffs;
567   O << "]";
568 }
569
570 void ARMAsmPrinter::printAddrMode3OffsetOperand(const MachineInstr *MI, int Op){
571   const MachineOperand &MO1 = MI->getOperand(Op);
572   const MachineOperand &MO2 = MI->getOperand(Op+1);
573
574   if (MO1.getReg()) {
575     O << (char)ARM_AM::getAM3Op(MO2.getImm())
576       << TRI->getAsmName(MO1.getReg());
577     return;
578   }
579
580   unsigned ImmOffs = ARM_AM::getAM3Offset(MO2.getImm());
581   assert(ImmOffs && "Malformed indexed load / store!");
582   O << "#"
583     << (char)ARM_AM::getAM3Op(MO2.getImm())
584     << ImmOffs;
585 }
586   
587 void ARMAsmPrinter::printAddrMode4Operand(const MachineInstr *MI, int Op,
588                                           const char *Modifier) {
589   const MachineOperand &MO1 = MI->getOperand(Op);
590   const MachineOperand &MO2 = MI->getOperand(Op+1);
591   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
592   if (Modifier && strcmp(Modifier, "submode") == 0) {
593     if (MO1.getReg() == ARM::SP) {
594       // FIXME
595       bool isLDM = (MI->getOpcode() == ARM::LDM ||
596                     MI->getOpcode() == ARM::LDM_RET ||
597                     MI->getOpcode() == ARM::t2LDM ||
598                     MI->getOpcode() == ARM::t2LDM_RET);
599       O << ARM_AM::getAMSubModeAltStr(Mode, isLDM);
600     } else
601       O << ARM_AM::getAMSubModeStr(Mode);
602   } else {
603     printOperand(MI, Op);
604     if (ARM_AM::getAM4WBFlag(MO2.getImm()))
605       O << "!";
606   }
607 }
608
609 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
610                                           const char *Modifier) {
611   const MachineOperand &MO1 = MI->getOperand(Op);
612   const MachineOperand &MO2 = MI->getOperand(Op+1);
613
614   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
615     printOperand(MI, Op);
616     return;
617   }
618   
619   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
620
621   if (Modifier && strcmp(Modifier, "submode") == 0) {
622     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
623     if (MO1.getReg() == ARM::SP) {
624       bool isFLDM = (MI->getOpcode() == ARM::FLDMD ||
625                      MI->getOpcode() == ARM::FLDMS);
626       O << ARM_AM::getAMSubModeAltStr(Mode, isFLDM);
627     } else
628       O << ARM_AM::getAMSubModeStr(Mode);
629     return;
630   } else if (Modifier && strcmp(Modifier, "base") == 0) {
631     // Used for FSTM{D|S} and LSTM{D|S} operations.
632     O << TRI->getAsmName(MO1.getReg());
633     if (ARM_AM::getAM5WBFlag(MO2.getImm()))
634       O << "!";
635     return;
636   }
637   
638   O << "[" << TRI->getAsmName(MO1.getReg());
639   
640   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
641     O << ", #"
642       << (char)ARM_AM::getAM5Op(MO2.getImm())
643       << ImmOffs*4;
644   }
645   O << "]";
646 }
647
648 void ARMAsmPrinter::printAddrMode6Operand(const MachineInstr *MI, int Op) {
649   const MachineOperand &MO1 = MI->getOperand(Op);
650   const MachineOperand &MO2 = MI->getOperand(Op+1);
651   const MachineOperand &MO3 = MI->getOperand(Op+2);
652
653   // FIXME: No support yet for specifying alignment.
654   O << "[" << TRI->getAsmName(MO1.getReg()) << "]";
655
656   if (ARM_AM::getAM6WBFlag(MO3.getImm())) {
657     if (MO2.getReg() == 0)
658       O << "!";
659     else
660       O << ", " << TRI->getAsmName(MO2.getReg());
661   }
662 }
663
664 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
665                                            const char *Modifier) {
666   if (Modifier && strcmp(Modifier, "label") == 0) {
667     printPCLabel(MI, Op+1);
668     return;
669   }
670
671   const MachineOperand &MO1 = MI->getOperand(Op);
672   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
673   O << "[pc, +" << TRI->getAsmName(MO1.getReg()) << "]";
674 }
675
676 void
677 ARMAsmPrinter::printBitfieldInvMaskImmOperand(const MachineInstr *MI, int Op) {
678   const MachineOperand &MO = MI->getOperand(Op);
679   uint32_t v = ~MO.getImm();
680   int32_t lsb = CountTrailingZeros_32(v);
681   int32_t width = (32 - CountLeadingZeros_32 (v)) - lsb;
682   assert(MO.isImm() && "Not a valid bf_inv_mask_imm value!");
683   O << "#" << lsb << ", #" << width;
684 }
685
686 //===--------------------------------------------------------------------===//
687
688 void
689 ARMAsmPrinter::printThumbITMask(const MachineInstr *MI, int Op) {
690   // (3 - the number of trailing zeros) is the number of then / else.
691   unsigned Mask = MI->getOperand(Op).getImm();
692   unsigned NumTZ = CountTrailingZeros_32(Mask);
693   assert(NumTZ <= 3 && "Invalid IT mask!");
694   for (unsigned Pos = 3, e = NumTZ; Pos > e; --Pos) {
695     bool T = (Mask & (1 << Pos)) != 0;
696     if (T)
697       O << 't';
698     else
699       O << 'e';
700   }
701 }
702
703 void
704 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op) {
705   const MachineOperand &MO1 = MI->getOperand(Op);
706   const MachineOperand &MO2 = MI->getOperand(Op+1);
707   O << "[" << TRI->getAsmName(MO1.getReg());
708   O << ", " << TRI->getAsmName(MO2.getReg()) << "]";
709 }
710
711 void
712 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
713                                             unsigned Scale) {
714   const MachineOperand &MO1 = MI->getOperand(Op);
715   const MachineOperand &MO2 = MI->getOperand(Op+1);
716   const MachineOperand &MO3 = MI->getOperand(Op+2);
717
718   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
719     printOperand(MI, Op);
720     return;
721   }
722
723   O << "[" << TRI->getAsmName(MO1.getReg());
724   if (MO3.getReg())
725     O << ", " << TRI->getAsmName(MO3.getReg());
726   else if (unsigned ImmOffs = MO2.getImm()) {
727     O << ", #" << ImmOffs;
728     if (Scale > 1)
729       O << " * " << Scale;
730   }
731   O << "]";
732 }
733
734 void
735 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op) {
736   printThumbAddrModeRI5Operand(MI, Op, 1);
737 }
738 void
739 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op) {
740   printThumbAddrModeRI5Operand(MI, Op, 2);
741 }
742 void
743 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op) {
744   printThumbAddrModeRI5Operand(MI, Op, 4);
745 }
746
747 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op) {
748   const MachineOperand &MO1 = MI->getOperand(Op);
749   const MachineOperand &MO2 = MI->getOperand(Op+1);
750   O << "[" << TRI->getAsmName(MO1.getReg());
751   if (unsigned ImmOffs = MO2.getImm())
752     O << ", #" << ImmOffs << " * 4";
753   O << "]";
754 }
755
756 //===--------------------------------------------------------------------===//
757
758 // Constant shifts t2_so_reg is a 2-operand unit corresponding to the Thumb2
759 // register with shift forms.
760 // REG 0   0           - e.g. R5
761 // REG IMM, SH_OPC     - e.g. R5, LSL #3
762 void ARMAsmPrinter::printT2SOOperand(const MachineInstr *MI, int OpNum) {
763   const MachineOperand &MO1 = MI->getOperand(OpNum);
764   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
765
766   unsigned Reg = MO1.getReg();
767   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
768   O << TRI->getAsmName(Reg);
769
770   // Print the shift opc.
771   O << ", "
772     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO2.getImm()))
773     << " ";
774
775   assert(MO2.isImm() && "Not a valid t2_so_reg value!");
776   O << "#" << ARM_AM::getSORegOffset(MO2.getImm());
777 }
778
779 void ARMAsmPrinter::printT2AddrModeImm12Operand(const MachineInstr *MI,
780                                                 int OpNum) {
781   const MachineOperand &MO1 = MI->getOperand(OpNum);
782   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
783
784   O << "[" << TRI->getAsmName(MO1.getReg());
785
786   unsigned OffImm = MO2.getImm();
787   if (OffImm)  // Don't print +0.
788     O << ", #+" << OffImm;
789   O << "]";
790 }
791
792 void ARMAsmPrinter::printT2AddrModeImm8Operand(const MachineInstr *MI,
793                                                int OpNum) {
794   const MachineOperand &MO1 = MI->getOperand(OpNum);
795   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
796
797   O << "[" << TRI->getAsmName(MO1.getReg());
798
799   int32_t OffImm = (int32_t)MO2.getImm();
800   // Don't print +0.
801   if (OffImm < 0)
802     O << ", #-" << -OffImm;
803   else if (OffImm > 0)
804     O << ", #+" << OffImm;
805   O << "]";
806 }
807
808 void ARMAsmPrinter::printT2AddrModeImm8s4Operand(const MachineInstr *MI,
809                                                  int OpNum) {
810   const MachineOperand &MO1 = MI->getOperand(OpNum);
811   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
812
813   O << "[" << TRI->getAsmName(MO1.getReg());
814
815   int32_t OffImm = (int32_t)MO2.getImm() / 4;
816   // Don't print +0.
817   if (OffImm < 0)
818     O << ", #-" << -OffImm << " * 4";
819   else if (OffImm > 0)
820     O << ", #+" << OffImm << " * 4";
821   O << "]";
822 }
823
824 void ARMAsmPrinter::printT2AddrModeImm8OffsetOperand(const MachineInstr *MI,
825                                                      int OpNum) {
826   const MachineOperand &MO1 = MI->getOperand(OpNum);
827   int32_t OffImm = (int32_t)MO1.getImm();
828   // Don't print +0.
829   if (OffImm < 0)
830     O << "#-" << -OffImm;
831   else if (OffImm > 0)
832     O << "#+" << OffImm;
833 }
834
835 void ARMAsmPrinter::printT2AddrModeSoRegOperand(const MachineInstr *MI,
836                                                 int OpNum) {
837   const MachineOperand &MO1 = MI->getOperand(OpNum);
838   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
839   const MachineOperand &MO3 = MI->getOperand(OpNum+2);
840
841   O << "[" << TRI->getAsmName(MO1.getReg());
842
843   if (MO2.getReg()) {
844     O << ", +" << TRI->getAsmName(MO2.getReg());
845
846     unsigned ShAmt = MO3.getImm();
847     if (ShAmt) {
848       assert(ShAmt <= 3 && "Not a valid Thumb2 addressing mode!");
849       O << ", lsl #" << ShAmt;
850     }
851   }
852   O << "]";
853 }
854
855
856 //===--------------------------------------------------------------------===//
857
858 void ARMAsmPrinter::printPredicateOperand(const MachineInstr *MI, int OpNum) {
859   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(OpNum).getImm();
860   if (CC != ARMCC::AL)
861     O << ARMCondCodeToString(CC);
862 }
863
864 void ARMAsmPrinter::printSBitModifierOperand(const MachineInstr *MI, int OpNum){
865   unsigned Reg = MI->getOperand(OpNum).getReg();
866   if (Reg) {
867     assert(Reg == ARM::CPSR && "Expect ARM CPSR register!");
868     O << 's';
869   }
870 }
871
872 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int OpNum) {
873   int Id = (int)MI->getOperand(OpNum).getImm();
874   O << TAI->getPrivateGlobalPrefix() << "PC" << Id;
875 }
876
877 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int OpNum) {
878   O << "{";
879   for (unsigned i = OpNum, e = MI->getNumOperands(); i != e; ++i) {
880     printOperand(MI, i);
881     if (i != e-1) O << ", ";
882   }
883   O << "}";
884 }
885
886 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNum,
887                                        const char *Modifier) {
888   assert(Modifier && "This operand only works with a modifier!");
889   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
890   // data itself.
891   if (!strcmp(Modifier, "label")) {
892     unsigned ID = MI->getOperand(OpNum).getImm();
893     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
894       << '_' << ID << ":\n";
895   } else {
896     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
897     unsigned CPI = MI->getOperand(OpNum).getIndex();
898
899     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
900     
901     if (MCPE.isMachineConstantPoolEntry()) {
902       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
903     } else {
904       EmitGlobalConstant(MCPE.Val.ConstVal);
905     }
906   }
907 }
908
909 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNum) {
910   assert(!Subtarget->isThumb2() && "Thumb2 should use double-jump jumptables!");
911
912   const MachineOperand &MO1 = MI->getOperand(OpNum);
913   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
914   unsigned JTI = MO1.getIndex();
915   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
916     << '_' << JTI << '_' << MO2.getImm() << ":\n";
917
918   const char *JTEntryDirective = TAI->getJumpTableDirective();
919   if (!JTEntryDirective)
920     JTEntryDirective = TAI->getData32bitsDirective();
921
922   const MachineFunction *MF = MI->getParent()->getParent();
923   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
924   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
925   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
926   bool UseSet= TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
927   SmallPtrSet<MachineBasicBlock*, 8> JTSets;
928   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
929     MachineBasicBlock *MBB = JTBBs[i];
930     bool isNew = JTSets.insert(MBB);
931
932     if (UseSet && isNew)
933       printPICJumpTableSetLabel(JTI, MO2.getImm(), MBB);
934
935     O << JTEntryDirective << ' ';
936     if (UseSet)
937       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
938         << '_' << JTI << '_' << MO2.getImm()
939         << "_set_" << MBB->getNumber();
940     else if (TM.getRelocationModel() == Reloc::PIC_) {
941       printBasicBlockLabel(MBB, false, false, false);
942       // If the arch uses custom Jump Table directives, don't calc relative to JT
943       if (!TAI->getJumpTableDirective()) 
944         O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
945           << getFunctionNumber() << '_' << JTI << '_' << MO2.getImm();
946     } else {
947       printBasicBlockLabel(MBB, false, false, false);
948     }
949     if (i != e-1)
950       O << '\n';
951   }
952 }
953
954 void ARMAsmPrinter::printJT2BlockOperand(const MachineInstr *MI, int OpNum) {
955   const MachineOperand &MO1 = MI->getOperand(OpNum);
956   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
957   unsigned JTI = MO1.getIndex();
958   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
959     << '_' << JTI << '_' << MO2.getImm() << ":\n";
960
961   const MachineFunction *MF = MI->getParent()->getParent();
962   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
963   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
964   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
965   bool ByteOffset = false, HalfWordOffset = false;
966   if (MI->getOpcode() == ARM::t2TBB)
967     ByteOffset = true;
968   else if (MI->getOpcode() == ARM::t2TBH)
969     HalfWordOffset = true;
970
971   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
972     MachineBasicBlock *MBB = JTBBs[i];
973     if (ByteOffset)
974       O << TAI->getData8bitsDirective();
975     else if (HalfWordOffset)
976       O << TAI->getData16bitsDirective();
977     if (ByteOffset || HalfWordOffset) {
978       O << '(';
979       printBasicBlockLabel(MBB, false, false, false);
980       O << "-" << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
981         << '_' << JTI << '_' << MO2.getImm() << ")/2";
982     } else {
983       O << "\tb.w ";
984       printBasicBlockLabel(MBB, false, false, false);
985     }
986     if (i != e-1)
987       O << '\n';
988   }
989
990   // Make sure the instruction that follows TBB is 2-byte aligned.
991   // FIXME: Constant island pass should insert an "ALIGN" instruction instead.
992   if (ByteOffset && (JTBBs.size() & 1)) {
993     O << '\n';
994     EmitAlignment(1);
995   }
996 }
997
998 void ARMAsmPrinter::printTBAddrMode(const MachineInstr *MI, int OpNum) {
999   O << "[pc, " << TRI->getAsmName(MI->getOperand(OpNum).getReg());
1000   if (MI->getOpcode() == ARM::t2TBH)
1001     O << ", lsl #1";
1002   O << ']';
1003 }
1004
1005
1006 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
1007                                     unsigned AsmVariant, const char *ExtraCode){
1008   // Does this asm operand have a single letter operand modifier?
1009   if (ExtraCode && ExtraCode[0]) {
1010     if (ExtraCode[1] != 0) return true; // Unknown modifier.
1011     
1012     switch (ExtraCode[0]) {
1013     default: return true;  // Unknown modifier.
1014     case 'a': // Print as a memory address.
1015       if (MI->getOperand(OpNum).isReg()) {
1016         O << "[" << TRI->getAsmName(MI->getOperand(OpNum).getReg()) << "]";
1017         return false;
1018       }
1019       // Fallthrough
1020     case 'c': // Don't print "#" before an immediate operand.
1021       printOperand(MI, OpNum, "no_hash");
1022       return false;
1023     case 'P': // Print a VFP double precision register.
1024       printOperand(MI, OpNum);
1025       return false;
1026     case 'Q':
1027       if (TM.getTargetData()->isLittleEndian())
1028         break;
1029       // Fallthrough
1030     case 'R':
1031       if (TM.getTargetData()->isBigEndian())
1032         break;
1033       // Fallthrough
1034     case 'H': // Write second word of DI / DF reference.  
1035       // Verify that this operand has two consecutive registers.
1036       if (!MI->getOperand(OpNum).isReg() ||
1037           OpNum+1 == MI->getNumOperands() ||
1038           !MI->getOperand(OpNum+1).isReg())
1039         return true;
1040       ++OpNum;   // Return the high-part.
1041     }
1042   }
1043   
1044   printOperand(MI, OpNum);
1045   return false;
1046 }
1047
1048 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1049                                           unsigned OpNum, unsigned AsmVariant,
1050                                           const char *ExtraCode) {
1051   if (ExtraCode && ExtraCode[0])
1052     return true; // Unknown modifier.
1053   printAddrMode2Operand(MI, OpNum);
1054   return false;
1055 }
1056
1057 void ARMAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
1058   ++EmittedInsts;
1059
1060   int Opc = MI->getOpcode();
1061   switch (Opc) {
1062   case ARM::CONSTPOOL_ENTRY:
1063     if (!InCPMode && AFI->isThumbFunction()) {
1064       EmitAlignment(2);
1065       InCPMode = true;
1066     }
1067     break;
1068   default: {
1069     if (InCPMode && AFI->isThumbFunction())
1070       InCPMode = false;
1071   }}
1072
1073   // Call the autogenerated instruction printer routines.
1074   printInstruction(MI);
1075 }
1076
1077 bool ARMAsmPrinter::doInitialization(Module &M) {
1078
1079   bool Result = AsmPrinter::doInitialization(M);
1080   DW = getAnalysisIfAvailable<DwarfWriter>();
1081
1082   // Use unified assembler syntax mode for Thumb.
1083   if (Subtarget->isThumb())
1084     O << "\t.syntax unified\n";
1085
1086   // Emit ARM Build Attributes
1087   if (Subtarget->isTargetELF()) {
1088     // CPU Type
1089     std::string CPUString = Subtarget->getCPUString();
1090     if (CPUString != "generic")
1091       O << "\t.cpu " << CPUString << '\n';
1092
1093     // FIXME: Emit FPU type
1094     if (Subtarget->hasVFP2())
1095       O << "\t.eabi_attribute " << ARMBuildAttrs::VFP_arch << ", 2\n";
1096
1097     // Signal various FP modes.
1098     if (!UnsafeFPMath)
1099       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_denormal << ", 1\n"
1100         << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_exceptions << ", 1\n";
1101
1102     if (FiniteOnlyFPMath())
1103       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 1\n";
1104     else
1105       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 3\n";
1106
1107     // 8-bytes alignment stuff.
1108     O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_needed << ", 1\n"
1109       << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_preserved << ", 1\n";
1110
1111     // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
1112     if (Subtarget->isAAPCS_ABI() && FloatABIType == FloatABI::Hard)
1113       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_HardFP_use << ", 3\n"
1114         << "\t.eabi_attribute " << ARMBuildAttrs::ABI_VFP_args << ", 1\n";
1115
1116     // FIXME: Should we signal R9 usage?
1117   }
1118
1119   return Result;
1120 }
1121
1122 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
1123 /// Don't print things like \\n or \\0.
1124 static void PrintUnmangledNameSafely(const Value *V, 
1125                                      formatted_raw_ostream &OS) {
1126   for (StringRef::iterator it = V->getName().begin(), 
1127          ie = V->getName().end(); it != ie; ++it)
1128     if (isprint(*it))
1129       OS << *it;
1130 }
1131
1132 void ARMAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
1133   const TargetData *TD = TM.getTargetData();
1134
1135   if (!GVar->hasInitializer())   // External global require no code
1136     return;
1137
1138   // Check to see if this is a special global used by LLVM, if so, emit it.
1139
1140   if (EmitSpecialLLVMGlobal(GVar)) {
1141     if (Subtarget->isTargetDarwin() &&
1142         TM.getRelocationModel() == Reloc::Static) {
1143       if (GVar->getName() == "llvm.global_ctors")
1144         O << ".reference .constructors_used\n";
1145       else if (GVar->getName() == "llvm.global_dtors")
1146         O << ".reference .destructors_used\n";
1147     }
1148     return;
1149   }
1150
1151   std::string name = Mang->getMangledName(GVar);
1152   Constant *C = GVar->getInitializer();
1153   const Type *Type = C->getType();
1154   unsigned Size = TD->getTypeAllocSize(Type);
1155   unsigned Align = TD->getPreferredAlignmentLog(GVar);
1156   bool isDarwin = Subtarget->isTargetDarwin();
1157
1158   printVisibility(name, GVar->getVisibility());
1159
1160   if (Subtarget->isTargetELF())
1161     O << "\t.type " << name << ",%object\n";
1162   
1163   const MCSection *TheSection =
1164     getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
1165   SwitchToSection(TheSection);
1166
1167   // FIXME: get this stuff from section kind flags.
1168   if (C->isNullValue() && !GVar->hasSection() && !GVar->isThreadLocal() &&
1169       // Don't put things that should go in the cstring section into "comm".
1170       !TheSection->getKind().isMergeableCString()) {
1171     if (GVar->hasExternalLinkage()) {
1172       if (const char *Directive = TAI->getZeroFillDirective()) {
1173         O << "\t.globl\t" << name << "\n";
1174         O << Directive << "__DATA, __common, " << name << ", "
1175           << Size << ", " << Align << "\n";
1176         return;
1177       }
1178     }
1179
1180     if (GVar->hasLocalLinkage() || GVar->isWeakForLinker()) {
1181       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
1182
1183       if (isDarwin) {
1184         if (GVar->hasLocalLinkage()) {
1185           O << TAI->getLCOMMDirective()  << name << "," << Size
1186             << ',' << Align;
1187         } else if (GVar->hasCommonLinkage()) {
1188           O << TAI->getCOMMDirective()  << name << "," << Size
1189             << ',' << Align;
1190         } else {
1191           SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang,TM));
1192           O << "\t.globl " << name << '\n'
1193             << TAI->getWeakDefDirective() << name << '\n';
1194           EmitAlignment(Align, GVar);
1195           O << name << ":";
1196           if (VerboseAsm) {
1197             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1198             PrintUnmangledNameSafely(GVar, O);
1199           }
1200           O << '\n';
1201           EmitGlobalConstant(C);
1202           return;
1203         }
1204       } else if (TAI->getLCOMMDirective() != NULL) {
1205         if (GVar->hasLocalLinkage()) {
1206           O << TAI->getLCOMMDirective() << name << "," << Size;
1207         } else {
1208           O << TAI->getCOMMDirective()  << name << "," << Size;
1209           if (TAI->getCOMMDirectiveTakesAlignment())
1210             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1211         }
1212       } else {
1213         if (GVar->hasLocalLinkage())
1214           O << "\t.local\t" << name << "\n";
1215         O << TAI->getCOMMDirective()  << name << "," << Size;
1216         if (TAI->getCOMMDirectiveTakesAlignment())
1217           O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1218       }
1219       if (VerboseAsm) {
1220         O << "\t\t" << TAI->getCommentString() << " ";
1221         PrintUnmangledNameSafely(GVar, O);
1222       }
1223       O << "\n";
1224       return;
1225     }
1226   }
1227   
1228   switch (GVar->getLinkage()) {
1229   case GlobalValue::CommonLinkage:
1230   case GlobalValue::LinkOnceAnyLinkage:
1231   case GlobalValue::LinkOnceODRLinkage:
1232   case GlobalValue::WeakAnyLinkage:
1233   case GlobalValue::WeakODRLinkage:
1234     if (isDarwin) {
1235       O << "\t.globl " << name << "\n"
1236         << "\t.weak_definition " << name << "\n";
1237     } else {
1238       O << "\t.weak " << name << "\n";
1239     }
1240     break;
1241   case GlobalValue::AppendingLinkage:
1242   // FIXME: appending linkage variables should go into a section of
1243   // their name or something.  For now, just emit them as external.
1244   case GlobalValue::ExternalLinkage:
1245     O << "\t.globl " << name << "\n";
1246     break;
1247   case GlobalValue::PrivateLinkage:
1248   case GlobalValue::LinkerPrivateLinkage:
1249   case GlobalValue::InternalLinkage:
1250     break;
1251   default:
1252     llvm_unreachable("Unknown linkage type!");
1253   }
1254
1255   EmitAlignment(Align, GVar);
1256   O << name << ":";
1257   if (VerboseAsm) {
1258     O << "\t\t\t\t" << TAI->getCommentString() << " ";
1259     PrintUnmangledNameSafely(GVar, O);
1260   }
1261   O << "\n";
1262   if (TAI->hasDotTypeDotSizeDirective())
1263     O << "\t.size " << name << ", " << Size << "\n";
1264
1265   EmitGlobalConstant(C);
1266   O << '\n';
1267 }
1268
1269
1270 bool ARMAsmPrinter::doFinalization(Module &M) {
1271   if (Subtarget->isTargetDarwin()) {
1272     // All darwin targets use mach-o.
1273     TargetLoweringObjectFileMachO &TLOFMacho = 
1274       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1275     
1276     O << '\n';
1277     
1278     if (!FnStubs.empty()) {
1279       const MCSection *StubSection;
1280       if (TM.getRelocationModel() == Reloc::PIC_)
1281         StubSection = TLOFMacho.getMachOSection(".section __TEXT,__picsymbolstu"
1282                                                 "b4,symbol_stubs,none,16", true,
1283                                                 SectionKind::getText());
1284       else
1285         StubSection = TLOFMacho.getMachOSection(".section __TEXT,__symbol_stub4"
1286                                                 ",symbol_stubs,none,12", true,
1287                                                 SectionKind::getText());
1288
1289       const MCSection *LazySymbolPointerSection
1290         = TLOFMacho.getMachOSection(".lazy_symbol_pointer", true,
1291                                     SectionKind::getMetadata());
1292     
1293       // Output stubs for dynamically-linked functions
1294       for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(),
1295            E = FnStubs.end(); I != E; ++I) {
1296         const FnStubInfo &Info = I->second;
1297         
1298         SwitchToSection(StubSection);
1299         EmitAlignment(2);
1300         O << "\t.code\t32\n";
1301
1302         O << Info.Stub << ":\n";
1303         O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1304         O << "\tldr ip, " << Info.SLP << '\n';
1305         if (TM.getRelocationModel() == Reloc::PIC_) {
1306           O << Info.SCV << ":\n";
1307           O << "\tadd ip, pc, ip\n";
1308         }
1309         O << "\tldr pc, [ip, #0]\n";
1310         O << Info.SLP << ":\n";
1311         O << "\t.long\t" << Info.LazyPtr;
1312         if (TM.getRelocationModel() == Reloc::PIC_)
1313           O << "-(" << Info.SCV << "+8)";
1314         O << '\n';
1315         
1316         SwitchToSection(LazySymbolPointerSection);
1317         O << Info.LazyPtr << ":\n";
1318         O << "\t.indirect_symbol " << I->getKeyData() << "\n";
1319         O << "\t.long\tdyld_stub_binding_helper\n";
1320       }
1321       O << '\n';
1322     }
1323     
1324     // Output non-lazy-pointers for external and common global variables.
1325     if (!GVNonLazyPtrs.empty()) {
1326       SwitchToSection(TLOFMacho.getMachOSection(".non_lazy_symbol_pointer",
1327                                                 true,
1328                                                 SectionKind::getMetadata()));
1329       for (StringMap<std::string>::iterator I = GVNonLazyPtrs.begin(),
1330            E = GVNonLazyPtrs.end(); I != E; ++I) {
1331         O << I->second << ":\n";
1332         O << "\t.indirect_symbol " << I->getKeyData() << "\n";
1333         O << "\t.long\t0\n";
1334       }
1335     }
1336
1337     if (!HiddenGVNonLazyPtrs.empty()) {
1338       SwitchToSection(getObjFileLowering().getDataSection());
1339       for (StringMap<std::string>::iterator I = HiddenGVNonLazyPtrs.begin(),
1340              E = HiddenGVNonLazyPtrs.end(); I != E; ++I) {
1341         EmitAlignment(2);
1342         O << I->second << ":\n";
1343         O << "\t.long " << I->getKeyData() << "\n";
1344       }
1345     }
1346
1347
1348     // Funny Darwin hack: This flag tells the linker that no global symbols
1349     // contain code that falls through to other global symbols (e.g. the obvious
1350     // implementation of multiple entry points).  If this doesn't occur, the
1351     // linker can safely perform dead code stripping.  Since LLVM never
1352     // generates code that does this, it is always safe to set.
1353     O << "\t.subsections_via_symbols\n";
1354   }
1355
1356   return AsmPrinter::doFinalization(M);
1357 }
1358
1359 // Force static initialization.
1360 extern "C" void LLVMInitializeARMAsmPrinter() { 
1361   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMTarget);
1362   RegisterAsmPrinter<ARMAsmPrinter> Y(TheThumbTarget);
1363 }