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