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