Shrinkify Thumb2 load / store multiple instructions.
[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/MCSectionMachO.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     void printLaneOperand(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     void 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 if (!strncmp(ACPV->getSymbol(), "L_lsda_", 7))
212           Name = ACPV->getSymbol();
213         else
214           Name = Mang->makeNameProper(ACPV->getSymbol());
215       }
216       O << Name;
217       
218       
219       
220       if (ACPV->hasModifier()) O << "(" << ACPV->getModifier() << ")";
221       if (ACPV->getPCAdjustment() != 0) {
222         O << "-(" << TAI->getPrivateGlobalPrefix() << "PC"
223           << ACPV->getLabelId()
224           << "+" << (unsigned)ACPV->getPCAdjustment();
225          if (ACPV->mustAddCurrentAddress())
226            O << "-.";
227          O << ")";
228       }
229       O << "\n";
230     }
231     
232     void getAnalysisUsage(AnalysisUsage &AU) const {
233       AsmPrinter::getAnalysisUsage(AU);
234       AU.setPreservesAll();
235       AU.addRequired<MachineModuleInfo>();
236       AU.addRequired<DwarfWriter>();
237     }
238   };
239 } // end of anonymous namespace
240
241 #include "ARMGenAsmWriter.inc"
242
243 /// runOnMachineFunction - This uses the printInstruction()
244 /// method to print assembly for each instruction.
245 ///
246 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
247   this->MF = &MF;
248
249   AFI = MF.getInfo<ARMFunctionInfo>();
250   MCP = MF.getConstantPool();
251
252   SetupMachineFunction(MF);
253   O << "\n";
254
255   // NOTE: we don't print out constant pools here, they are handled as
256   // instructions.
257
258   O << '\n';
259   
260   // Print out labels for the function.
261   const Function *F = MF.getFunction();
262   SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
263
264   switch (F->getLinkage()) {
265   default: llvm_unreachable("Unknown linkage type!");
266   case Function::PrivateLinkage:
267   case Function::LinkerPrivateLinkage:
268   case Function::InternalLinkage:
269     break;
270   case Function::ExternalLinkage:
271     O << "\t.globl\t" << CurrentFnName << "\n";
272     break;
273   case Function::WeakAnyLinkage:
274   case Function::WeakODRLinkage:
275   case Function::LinkOnceAnyLinkage:
276   case Function::LinkOnceODRLinkage:
277     if (Subtarget->isTargetDarwin()) {
278       O << "\t.globl\t" << CurrentFnName << "\n";
279       O << "\t.weak_definition\t" << CurrentFnName << "\n";
280     } else {
281       O << TAI->getWeakRefDirective() << CurrentFnName << "\n";
282     }
283     break;
284   }
285
286   printVisibility(CurrentFnName, F->getVisibility());
287
288   if (AFI->isThumbFunction()) {
289     EmitAlignment(MF.getAlignment(), F, AFI->getAlign());
290     O << "\t.code\t16\n";
291     O << "\t.thumb_func";
292     if (Subtarget->isTargetDarwin())
293       O << "\t" << CurrentFnName;
294     O << "\n";
295     InCPMode = false;
296   } else {
297     EmitAlignment(MF.getAlignment(), F);
298   }
299
300   O << CurrentFnName << ":\n";
301   // Emit pre-function debug information.
302   DW->BeginFunction(&MF);
303
304   if (Subtarget->isTargetDarwin()) {
305     // If the function is empty, then we need to emit *something*. Otherwise,
306     // the function's label might be associated with something that it wasn't
307     // meant to be associated with. We emit a noop in this situation.
308     MachineFunction::iterator I = MF.begin();
309
310     if (++I == MF.end() && MF.front().empty())
311       O << "\tnop\n";
312   }
313
314   // Print out code for the function.
315   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
316        I != E; ++I) {
317     // Print a label for the basic block.
318     if (I != MF.begin()) {
319       printBasicBlockLabel(I, true, true, VerboseAsm);
320       O << '\n';
321     }
322     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
323          II != E; ++II) {
324       // Print the assembly for the instruction.
325       printMachineInstruction(II);
326     }
327   }
328
329   if (TAI->hasDotTypeDotSizeDirective())
330     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
331
332   // Emit post-function debug information.
333   DW->EndFunction(&MF);
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, "lane") == 0) {
352         unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(Reg);
353         unsigned DReg = TRI->getMatchingSuperReg(Reg, RegNum & 1 ? 0 : 1,
354                                                  &ARM::DPRRegClass);
355         O << TRI->getAsmName(DReg) << '[' << (RegNum & 1) << ']';
356       } else {
357         O << TRI->getAsmName(Reg);
358       }
359     } else
360       llvm_unreachable("not implemented");
361     break;
362   }
363   case MachineOperand::MO_Immediate: {
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 if (Modifier && strcmp(Modifier, "wide") == 0) {
608     ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
609     if (Mode == ARM_AM::ia)
610       O << ".w";
611   } else {
612     printOperand(MI, Op);
613     if (ARM_AM::getAM4WBFlag(MO2.getImm()))
614       O << "!";
615   }
616 }
617
618 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
619                                           const char *Modifier) {
620   const MachineOperand &MO1 = MI->getOperand(Op);
621   const MachineOperand &MO2 = MI->getOperand(Op+1);
622
623   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
624     printOperand(MI, Op);
625     return;
626   }
627   
628   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
629
630   if (Modifier && strcmp(Modifier, "submode") == 0) {
631     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
632     if (MO1.getReg() == ARM::SP) {
633       bool isFLDM = (MI->getOpcode() == ARM::FLDMD ||
634                      MI->getOpcode() == ARM::FLDMS);
635       O << ARM_AM::getAMSubModeAltStr(Mode, isFLDM);
636     } else
637       O << ARM_AM::getAMSubModeStr(Mode);
638     return;
639   } else if (Modifier && strcmp(Modifier, "base") == 0) {
640     // Used for FSTM{D|S} and LSTM{D|S} operations.
641     O << TRI->getAsmName(MO1.getReg());
642     if (ARM_AM::getAM5WBFlag(MO2.getImm()))
643       O << "!";
644     return;
645   }
646   
647   O << "[" << TRI->getAsmName(MO1.getReg());
648   
649   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
650     O << ", #"
651       << (char)ARM_AM::getAM5Op(MO2.getImm())
652       << ImmOffs*4;
653   }
654   O << "]";
655 }
656
657 void ARMAsmPrinter::printAddrMode6Operand(const MachineInstr *MI, int Op) {
658   const MachineOperand &MO1 = MI->getOperand(Op);
659   const MachineOperand &MO2 = MI->getOperand(Op+1);
660   const MachineOperand &MO3 = MI->getOperand(Op+2);
661
662   // FIXME: No support yet for specifying alignment.
663   O << "[" << TRI->getAsmName(MO1.getReg()) << "]";
664
665   if (ARM_AM::getAM6WBFlag(MO3.getImm())) {
666     if (MO2.getReg() == 0)
667       O << "!";
668     else
669       O << ", " << TRI->getAsmName(MO2.getReg());
670   }
671 }
672
673 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
674                                            const char *Modifier) {
675   if (Modifier && strcmp(Modifier, "label") == 0) {
676     printPCLabel(MI, Op+1);
677     return;
678   }
679
680   const MachineOperand &MO1 = MI->getOperand(Op);
681   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
682   O << "[pc, +" << TRI->getAsmName(MO1.getReg()) << "]";
683 }
684
685 void
686 ARMAsmPrinter::printBitfieldInvMaskImmOperand(const MachineInstr *MI, int Op) {
687   const MachineOperand &MO = MI->getOperand(Op);
688   uint32_t v = ~MO.getImm();
689   int32_t lsb = CountTrailingZeros_32(v);
690   int32_t width = (32 - CountLeadingZeros_32 (v)) - lsb;
691   assert(MO.isImm() && "Not a valid bf_inv_mask_imm value!");
692   O << "#" << lsb << ", #" << width;
693 }
694
695 //===--------------------------------------------------------------------===//
696
697 void
698 ARMAsmPrinter::printThumbITMask(const MachineInstr *MI, int Op) {
699   // (3 - the number of trailing zeros) is the number of then / else.
700   unsigned Mask = MI->getOperand(Op).getImm();
701   unsigned NumTZ = CountTrailingZeros_32(Mask);
702   assert(NumTZ <= 3 && "Invalid IT mask!");
703   for (unsigned Pos = 3, e = NumTZ; Pos > e; --Pos) {
704     bool T = (Mask & (1 << Pos)) != 0;
705     if (T)
706       O << 't';
707     else
708       O << 'e';
709   }
710 }
711
712 void
713 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op) {
714   const MachineOperand &MO1 = MI->getOperand(Op);
715   const MachineOperand &MO2 = MI->getOperand(Op+1);
716   O << "[" << TRI->getAsmName(MO1.getReg());
717   O << ", " << TRI->getAsmName(MO2.getReg()) << "]";
718 }
719
720 void
721 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
722                                             unsigned Scale) {
723   const MachineOperand &MO1 = MI->getOperand(Op);
724   const MachineOperand &MO2 = MI->getOperand(Op+1);
725   const MachineOperand &MO3 = MI->getOperand(Op+2);
726
727   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
728     printOperand(MI, Op);
729     return;
730   }
731
732   O << "[" << TRI->getAsmName(MO1.getReg());
733   if (MO3.getReg())
734     O << ", " << TRI->getAsmName(MO3.getReg());
735   else if (unsigned ImmOffs = MO2.getImm()) {
736     O << ", #" << ImmOffs;
737     if (Scale > 1)
738       O << " * " << Scale;
739   }
740   O << "]";
741 }
742
743 void
744 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op) {
745   printThumbAddrModeRI5Operand(MI, Op, 1);
746 }
747 void
748 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op) {
749   printThumbAddrModeRI5Operand(MI, Op, 2);
750 }
751 void
752 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op) {
753   printThumbAddrModeRI5Operand(MI, Op, 4);
754 }
755
756 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op) {
757   const MachineOperand &MO1 = MI->getOperand(Op);
758   const MachineOperand &MO2 = MI->getOperand(Op+1);
759   O << "[" << TRI->getAsmName(MO1.getReg());
760   if (unsigned ImmOffs = MO2.getImm())
761     O << ", #" << ImmOffs << " * 4";
762   O << "]";
763 }
764
765 //===--------------------------------------------------------------------===//
766
767 // Constant shifts t2_so_reg is a 2-operand unit corresponding to the Thumb2
768 // register with shift forms.
769 // REG 0   0           - e.g. R5
770 // REG IMM, SH_OPC     - e.g. R5, LSL #3
771 void ARMAsmPrinter::printT2SOOperand(const MachineInstr *MI, int OpNum) {
772   const MachineOperand &MO1 = MI->getOperand(OpNum);
773   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
774
775   unsigned Reg = MO1.getReg();
776   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
777   O << TRI->getAsmName(Reg);
778
779   // Print the shift opc.
780   O << ", "
781     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO2.getImm()))
782     << " ";
783
784   assert(MO2.isImm() && "Not a valid t2_so_reg value!");
785   O << "#" << ARM_AM::getSORegOffset(MO2.getImm());
786 }
787
788 void ARMAsmPrinter::printT2AddrModeImm12Operand(const MachineInstr *MI,
789                                                 int OpNum) {
790   const MachineOperand &MO1 = MI->getOperand(OpNum);
791   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
792
793   O << "[" << TRI->getAsmName(MO1.getReg());
794
795   unsigned OffImm = MO2.getImm();
796   if (OffImm)  // Don't print +0.
797     O << ", #+" << OffImm;
798   O << "]";
799 }
800
801 void ARMAsmPrinter::printT2AddrModeImm8Operand(const MachineInstr *MI,
802                                                int OpNum) {
803   const MachineOperand &MO1 = MI->getOperand(OpNum);
804   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
805
806   O << "[" << TRI->getAsmName(MO1.getReg());
807
808   int32_t OffImm = (int32_t)MO2.getImm();
809   // Don't print +0.
810   if (OffImm < 0)
811     O << ", #-" << -OffImm;
812   else if (OffImm > 0)
813     O << ", #+" << OffImm;
814   O << "]";
815 }
816
817 void ARMAsmPrinter::printT2AddrModeImm8s4Operand(const MachineInstr *MI,
818                                                  int OpNum) {
819   const MachineOperand &MO1 = MI->getOperand(OpNum);
820   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
821
822   O << "[" << TRI->getAsmName(MO1.getReg());
823
824   int32_t OffImm = (int32_t)MO2.getImm() / 4;
825   // Don't print +0.
826   if (OffImm < 0)
827     O << ", #-" << -OffImm << " * 4";
828   else if (OffImm > 0)
829     O << ", #+" << OffImm << " * 4";
830   O << "]";
831 }
832
833 void ARMAsmPrinter::printT2AddrModeImm8OffsetOperand(const MachineInstr *MI,
834                                                      int OpNum) {
835   const MachineOperand &MO1 = MI->getOperand(OpNum);
836   int32_t OffImm = (int32_t)MO1.getImm();
837   // Don't print +0.
838   if (OffImm < 0)
839     O << "#-" << -OffImm;
840   else if (OffImm > 0)
841     O << "#+" << OffImm;
842 }
843
844 void ARMAsmPrinter::printT2AddrModeSoRegOperand(const MachineInstr *MI,
845                                                 int OpNum) {
846   const MachineOperand &MO1 = MI->getOperand(OpNum);
847   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
848   const MachineOperand &MO3 = MI->getOperand(OpNum+2);
849
850   O << "[" << TRI->getAsmName(MO1.getReg());
851
852   assert(MO2.getReg() && "Invalid so_reg load / store address!");
853   O << ", " << TRI->getAsmName(MO2.getReg());
854
855   unsigned ShAmt = MO3.getImm();
856   if (ShAmt) {
857     assert(ShAmt <= 3 && "Not a valid Thumb2 addressing mode!");
858     O << ", lsl #" << ShAmt;
859   }
860   O << "]";
861 }
862
863
864 //===--------------------------------------------------------------------===//
865
866 void ARMAsmPrinter::printPredicateOperand(const MachineInstr *MI, int OpNum) {
867   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(OpNum).getImm();
868   if (CC != ARMCC::AL)
869     O << ARMCondCodeToString(CC);
870 }
871
872 void ARMAsmPrinter::printSBitModifierOperand(const MachineInstr *MI, int OpNum){
873   unsigned Reg = MI->getOperand(OpNum).getReg();
874   if (Reg) {
875     assert(Reg == ARM::CPSR && "Expect ARM CPSR register!");
876     O << 's';
877   }
878 }
879
880 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int OpNum) {
881   int Id = (int)MI->getOperand(OpNum).getImm();
882   O << TAI->getPrivateGlobalPrefix() << "PC" << Id;
883 }
884
885 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int OpNum) {
886   O << "{";
887   for (unsigned i = OpNum, e = MI->getNumOperands(); i != e; ++i) {
888     if (MI->getOperand(i).isImplicit())
889       continue;
890     if ((int)i != OpNum) O << ", ";
891     printOperand(MI, i);
892   }
893   O << "}";
894 }
895
896 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNum,
897                                        const char *Modifier) {
898   assert(Modifier && "This operand only works with a modifier!");
899   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
900   // data itself.
901   if (!strcmp(Modifier, "label")) {
902     unsigned ID = MI->getOperand(OpNum).getImm();
903     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
904       << '_' << ID << ":\n";
905   } else {
906     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
907     unsigned CPI = MI->getOperand(OpNum).getIndex();
908
909     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
910     
911     if (MCPE.isMachineConstantPoolEntry()) {
912       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
913     } else {
914       EmitGlobalConstant(MCPE.Val.ConstVal);
915     }
916   }
917 }
918
919 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNum) {
920   assert(!Subtarget->isThumb2() && "Thumb2 should use double-jump jumptables!");
921
922   const MachineOperand &MO1 = MI->getOperand(OpNum);
923   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
924   unsigned JTI = MO1.getIndex();
925   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
926     << '_' << JTI << '_' << MO2.getImm() << ":\n";
927
928   const char *JTEntryDirective = TAI->getData32bitsDirective();
929
930   const MachineFunction *MF = MI->getParent()->getParent();
931   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
932   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
933   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
934   bool UseSet= TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
935   SmallPtrSet<MachineBasicBlock*, 8> JTSets;
936   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
937     MachineBasicBlock *MBB = JTBBs[i];
938     bool isNew = JTSets.insert(MBB);
939
940     if (UseSet && isNew)
941       printPICJumpTableSetLabel(JTI, MO2.getImm(), MBB);
942
943     O << JTEntryDirective << ' ';
944     if (UseSet)
945       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
946         << '_' << JTI << '_' << MO2.getImm()
947         << "_set_" << MBB->getNumber();
948     else if (TM.getRelocationModel() == Reloc::PIC_) {
949       printBasicBlockLabel(MBB, false, false, false);
950       O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
951         << getFunctionNumber() << '_' << JTI << '_' << MO2.getImm();
952     } else {
953       printBasicBlockLabel(MBB, false, false, false);
954     }
955     if (i != e-1)
956       O << '\n';
957   }
958 }
959
960 void ARMAsmPrinter::printJT2BlockOperand(const MachineInstr *MI, int OpNum) {
961   const MachineOperand &MO1 = MI->getOperand(OpNum);
962   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
963   unsigned JTI = MO1.getIndex();
964   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
965     << '_' << JTI << '_' << MO2.getImm() << ":\n";
966
967   const MachineFunction *MF = MI->getParent()->getParent();
968   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
969   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
970   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
971   bool ByteOffset = false, HalfWordOffset = false;
972   if (MI->getOpcode() == ARM::t2TBB)
973     ByteOffset = true;
974   else if (MI->getOpcode() == ARM::t2TBH)
975     HalfWordOffset = true;
976
977   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
978     MachineBasicBlock *MBB = JTBBs[i];
979     if (ByteOffset)
980       O << TAI->getData8bitsDirective();
981     else if (HalfWordOffset)
982       O << TAI->getData16bitsDirective();
983     if (ByteOffset || HalfWordOffset) {
984       O << '(';
985       printBasicBlockLabel(MBB, false, false, false);
986       O << "-" << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
987         << '_' << JTI << '_' << MO2.getImm() << ")/2";
988     } else {
989       O << "\tb.w ";
990       printBasicBlockLabel(MBB, false, false, false);
991     }
992     if (i != e-1)
993       O << '\n';
994   }
995
996   // Make sure the instruction that follows TBB is 2-byte aligned.
997   // FIXME: Constant island pass should insert an "ALIGN" instruction instead.
998   if (ByteOffset && (JTBBs.size() & 1)) {
999     O << '\n';
1000     EmitAlignment(1);
1001   }
1002 }
1003
1004 void ARMAsmPrinter::printTBAddrMode(const MachineInstr *MI, int OpNum) {
1005   O << "[pc, " << TRI->getAsmName(MI->getOperand(OpNum).getReg());
1006   if (MI->getOpcode() == ARM::t2TBH)
1007     O << ", lsl #1";
1008   O << ']';
1009 }
1010
1011 void ARMAsmPrinter::printLaneOperand(const MachineInstr *MI, int OpNum) {
1012   O << MI->getOperand(OpNum).getImm();
1013 }
1014
1015 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
1016                                     unsigned AsmVariant, const char *ExtraCode){
1017   // Does this asm operand have a single letter operand modifier?
1018   if (ExtraCode && ExtraCode[0]) {
1019     if (ExtraCode[1] != 0) return true; // Unknown modifier.
1020
1021     switch (ExtraCode[0]) {
1022     default: return true;  // Unknown modifier.
1023     case 'a': // Print as a memory address.
1024       if (MI->getOperand(OpNum).isReg()) {
1025         O << "[" << TRI->getAsmName(MI->getOperand(OpNum).getReg()) << "]";
1026         return false;
1027       }
1028       // Fallthrough
1029     case 'c': // Don't print "#" before an immediate operand.
1030       printLaneOperand(MI, OpNum);
1031       return false;
1032     case 'P': // Print a VFP double precision register.
1033       printOperand(MI, OpNum);
1034       return false;
1035     case 'Q':
1036       if (TM.getTargetData()->isLittleEndian())
1037         break;
1038       // Fallthrough
1039     case 'R':
1040       if (TM.getTargetData()->isBigEndian())
1041         break;
1042       // Fallthrough
1043     case 'H': // Write second word of DI / DF reference.  
1044       // Verify that this operand has two consecutive registers.
1045       if (!MI->getOperand(OpNum).isReg() ||
1046           OpNum+1 == MI->getNumOperands() ||
1047           !MI->getOperand(OpNum+1).isReg())
1048         return true;
1049       ++OpNum;   // Return the high-part.
1050     }
1051   }
1052   
1053   printOperand(MI, OpNum);
1054   return false;
1055 }
1056
1057 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1058                                           unsigned OpNum, unsigned AsmVariant,
1059                                           const char *ExtraCode) {
1060   if (ExtraCode && ExtraCode[0])
1061     return true; // Unknown modifier.
1062   printAddrMode2Operand(MI, OpNum);
1063   return false;
1064 }
1065
1066 void ARMAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
1067   ++EmittedInsts;
1068
1069   int Opc = MI->getOpcode();
1070   switch (Opc) {
1071   case ARM::CONSTPOOL_ENTRY:
1072     if (!InCPMode && AFI->isThumbFunction()) {
1073       EmitAlignment(2);
1074       InCPMode = true;
1075     }
1076     break;
1077   default: {
1078     if (InCPMode && AFI->isThumbFunction())
1079       InCPMode = false;
1080   }}
1081
1082   // Call the autogenerated instruction printer routines.
1083   printInstruction(MI);
1084 }
1085
1086 bool ARMAsmPrinter::doInitialization(Module &M) {
1087
1088   bool Result = AsmPrinter::doInitialization(M);
1089   DW = getAnalysisIfAvailable<DwarfWriter>();
1090
1091   // Use unified assembler syntax mode for Thumb.
1092   if (Subtarget->isThumb())
1093     O << "\t.syntax unified\n";
1094
1095   // Emit ARM Build Attributes
1096   if (Subtarget->isTargetELF()) {
1097     // CPU Type
1098     std::string CPUString = Subtarget->getCPUString();
1099     if (CPUString != "generic")
1100       O << "\t.cpu " << CPUString << '\n';
1101
1102     // FIXME: Emit FPU type
1103     if (Subtarget->hasVFP2())
1104       O << "\t.eabi_attribute " << ARMBuildAttrs::VFP_arch << ", 2\n";
1105
1106     // Signal various FP modes.
1107     if (!UnsafeFPMath)
1108       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_denormal << ", 1\n"
1109         << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_exceptions << ", 1\n";
1110
1111     if (FiniteOnlyFPMath())
1112       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 1\n";
1113     else
1114       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 3\n";
1115
1116     // 8-bytes alignment stuff.
1117     O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_needed << ", 1\n"
1118       << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_preserved << ", 1\n";
1119
1120     // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
1121     if (Subtarget->isAAPCS_ABI() && FloatABIType == FloatABI::Hard)
1122       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_HardFP_use << ", 3\n"
1123         << "\t.eabi_attribute " << ARMBuildAttrs::ABI_VFP_args << ", 1\n";
1124
1125     // FIXME: Should we signal R9 usage?
1126   }
1127
1128   return Result;
1129 }
1130
1131 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
1132 /// Don't print things like \\n or \\0.
1133 static void PrintUnmangledNameSafely(const Value *V, 
1134                                      formatted_raw_ostream &OS) {
1135   for (StringRef::iterator it = V->getName().begin(), 
1136          ie = V->getName().end(); it != ie; ++it)
1137     if (isprint(*it))
1138       OS << *it;
1139 }
1140
1141 void ARMAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
1142   const TargetData *TD = TM.getTargetData();
1143
1144   if (!GVar->hasInitializer())   // External global require no code
1145     return;
1146
1147   // Check to see if this is a special global used by LLVM, if so, emit it.
1148
1149   if (EmitSpecialLLVMGlobal(GVar)) {
1150     if (Subtarget->isTargetDarwin() &&
1151         TM.getRelocationModel() == Reloc::Static) {
1152       if (GVar->getName() == "llvm.global_ctors")
1153         O << ".reference .constructors_used\n";
1154       else if (GVar->getName() == "llvm.global_dtors")
1155         O << ".reference .destructors_used\n";
1156     }
1157     return;
1158   }
1159
1160   std::string name = Mang->getMangledName(GVar);
1161   Constant *C = GVar->getInitializer();
1162   const Type *Type = C->getType();
1163   unsigned Size = TD->getTypeAllocSize(Type);
1164   unsigned Align = TD->getPreferredAlignmentLog(GVar);
1165   bool isDarwin = Subtarget->isTargetDarwin();
1166
1167   printVisibility(name, GVar->getVisibility());
1168
1169   if (Subtarget->isTargetELF())
1170     O << "\t.type " << name << ",%object\n";
1171   
1172   const MCSection *TheSection =
1173     getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
1174   SwitchToSection(TheSection);
1175
1176   // FIXME: get this stuff from section kind flags.
1177   if (C->isNullValue() && !GVar->hasSection() && !GVar->isThreadLocal() &&
1178       // Don't put things that should go in the cstring section into "comm".
1179       !TheSection->getKind().isMergeableCString()) {
1180     if (GVar->hasExternalLinkage()) {
1181       if (const char *Directive = TAI->getZeroFillDirective()) {
1182         O << "\t.globl\t" << name << "\n";
1183         O << Directive << "__DATA, __common, " << name << ", "
1184           << Size << ", " << Align << "\n";
1185         return;
1186       }
1187     }
1188
1189     if (GVar->hasLocalLinkage() || GVar->isWeakForLinker()) {
1190       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
1191
1192       if (isDarwin) {
1193         if (GVar->hasLocalLinkage()) {
1194           O << TAI->getLCOMMDirective()  << name << "," << Size
1195             << ',' << Align;
1196         } else if (GVar->hasCommonLinkage()) {
1197           O << TAI->getCOMMDirective()  << name << "," << Size
1198             << ',' << Align;
1199         } else {
1200           SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang,TM));
1201           O << "\t.globl " << name << '\n'
1202             << TAI->getWeakDefDirective() << name << '\n';
1203           EmitAlignment(Align, GVar);
1204           O << name << ":";
1205           if (VerboseAsm) {
1206             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1207             PrintUnmangledNameSafely(GVar, O);
1208           }
1209           O << '\n';
1210           EmitGlobalConstant(C);
1211           return;
1212         }
1213       } else if (TAI->getLCOMMDirective() != NULL) {
1214         if (GVar->hasLocalLinkage()) {
1215           O << TAI->getLCOMMDirective() << name << "," << Size;
1216         } else {
1217           O << TAI->getCOMMDirective()  << name << "," << Size;
1218           if (TAI->getCOMMDirectiveTakesAlignment())
1219             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1220         }
1221       } else {
1222         if (GVar->hasLocalLinkage())
1223           O << "\t.local\t" << name << "\n";
1224         O << TAI->getCOMMDirective()  << name << "," << Size;
1225         if (TAI->getCOMMDirectiveTakesAlignment())
1226           O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1227       }
1228       if (VerboseAsm) {
1229         O << "\t\t" << TAI->getCommentString() << " ";
1230         PrintUnmangledNameSafely(GVar, O);
1231       }
1232       O << "\n";
1233       return;
1234     }
1235   }
1236   
1237   switch (GVar->getLinkage()) {
1238   case GlobalValue::CommonLinkage:
1239   case GlobalValue::LinkOnceAnyLinkage:
1240   case GlobalValue::LinkOnceODRLinkage:
1241   case GlobalValue::WeakAnyLinkage:
1242   case GlobalValue::WeakODRLinkage:
1243     if (isDarwin) {
1244       O << "\t.globl " << name << "\n"
1245         << "\t.weak_definition " << name << "\n";
1246     } else {
1247       O << "\t.weak " << name << "\n";
1248     }
1249     break;
1250   case GlobalValue::AppendingLinkage:
1251   // FIXME: appending linkage variables should go into a section of
1252   // their name or something.  For now, just emit them as external.
1253   case GlobalValue::ExternalLinkage:
1254     O << "\t.globl " << name << "\n";
1255     break;
1256   case GlobalValue::PrivateLinkage:
1257   case GlobalValue::LinkerPrivateLinkage:
1258   case GlobalValue::InternalLinkage:
1259     break;
1260   default:
1261     llvm_unreachable("Unknown linkage type!");
1262   }
1263
1264   EmitAlignment(Align, GVar);
1265   O << name << ":";
1266   if (VerboseAsm) {
1267     O << "\t\t\t\t" << TAI->getCommentString() << " ";
1268     PrintUnmangledNameSafely(GVar, O);
1269   }
1270   O << "\n";
1271   if (TAI->hasDotTypeDotSizeDirective())
1272     O << "\t.size " << name << ", " << Size << "\n";
1273
1274   EmitGlobalConstant(C);
1275   O << '\n';
1276 }
1277
1278
1279 bool ARMAsmPrinter::doFinalization(Module &M) {
1280   if (Subtarget->isTargetDarwin()) {
1281     // All darwin targets use mach-o.
1282     TargetLoweringObjectFileMachO &TLOFMacho = 
1283       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1284     
1285     O << '\n';
1286     
1287     if (!FnStubs.empty()) {
1288       unsigned StubSize = 12;
1289       const char *StubSectionName = "__symbol_stub4";
1290       
1291       if (TM.getRelocationModel() == Reloc::PIC_) {
1292         StubSize = 16;
1293         StubSectionName = "__picsymbolstub4";
1294       }
1295       
1296       const MCSection *StubSection
1297         = TLOFMacho.getMachOSection("__TEXT", StubSectionName,
1298                                     MCSectionMachO::S_SYMBOL_STUBS,
1299                                     StubSize, SectionKind::getText());
1300
1301       const MCSection *LazySymbolPointerSection
1302         = TLOFMacho.getLazySymbolPointerSection();
1303     
1304       // Output stubs for dynamically-linked functions
1305       for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(),
1306            E = FnStubs.end(); I != E; ++I) {
1307         const FnStubInfo &Info = I->second;
1308         
1309         SwitchToSection(StubSection);
1310         EmitAlignment(2);
1311         O << "\t.code\t32\n";
1312
1313         O << Info.Stub << ":\n";
1314         O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1315         O << "\tldr ip, " << Info.SLP << '\n';
1316         if (TM.getRelocationModel() == Reloc::PIC_) {
1317           O << Info.SCV << ":\n";
1318           O << "\tadd ip, pc, ip\n";
1319         }
1320         O << "\tldr pc, [ip, #0]\n";
1321         O << Info.SLP << ":\n";
1322         O << "\t.long\t" << Info.LazyPtr;
1323         if (TM.getRelocationModel() == Reloc::PIC_)
1324           O << "-(" << Info.SCV << "+8)";
1325         O << '\n';
1326         
1327         SwitchToSection(LazySymbolPointerSection);
1328         O << Info.LazyPtr << ":\n";
1329         O << "\t.indirect_symbol " << I->getKeyData() << "\n";
1330         O << "\t.long\tdyld_stub_binding_helper\n";
1331       }
1332       O << '\n';
1333     }
1334     
1335     // Output non-lazy-pointers for external and common global variables.
1336     if (!GVNonLazyPtrs.empty()) {
1337       // Switch with ".non_lazy_symbol_pointer" directive.
1338       SwitchToSection(TLOFMacho.getNonLazySymbolPointerSection());
1339       EmitAlignment(2);
1340       for (StringMap<std::string>::iterator I = GVNonLazyPtrs.begin(),
1341            E = GVNonLazyPtrs.end(); I != E; ++I) {
1342         O << I->second << ":\n";
1343         O << "\t.indirect_symbol " << I->getKeyData() << "\n";
1344         O << "\t.long\t0\n";
1345       }
1346     }
1347
1348     if (!HiddenGVNonLazyPtrs.empty()) {
1349       SwitchToSection(getObjFileLowering().getDataSection());
1350       EmitAlignment(2);
1351       for (StringMap<std::string>::iterator I = HiddenGVNonLazyPtrs.begin(),
1352              E = HiddenGVNonLazyPtrs.end(); I != E; ++I) {
1353         O << I->second << ":\n";
1354         O << "\t.long " << I->getKeyData() << "\n";
1355       }
1356     }
1357
1358
1359     // Funny Darwin hack: This flag tells the linker that no global symbols
1360     // contain code that falls through to other global symbols (e.g. the obvious
1361     // implementation of multiple entry points).  If this doesn't occur, the
1362     // linker can safely perform dead code stripping.  Since LLVM never
1363     // generates code that does this, it is always safe to set.
1364     O << "\t.subsections_via_symbols\n";
1365   }
1366
1367   return AsmPrinter::doFinalization(M);
1368 }
1369
1370 // Force static initialization.
1371 extern "C" void LLVMInitializeARMAsmPrinter() { 
1372   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMTarget);
1373   RegisterAsmPrinter<ARMAsmPrinter> Y(TheThumbTarget);
1374 }