- Reorg Thumb load / store instructions. Combine each rr and ri pair of
[oota-llvm.git] / lib / Target / ARM / ARMAsmPrinter.cpp
1 //===-- ARMAsmPrinter.cpp - ARM LLVM assembly writer ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the "Instituto Nokia de Tecnologia" and
6 // is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file contains a printer that converts from our internal representation
12 // of machine-dependent LLVM code to GAS-format ARM assembly language.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "asm-printer"
17 #include "ARM.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/MachineDebugInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <cctype>
39 #include <iostream>
40 #include <set>
41 using namespace llvm;
42
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
44
45 namespace {
46   struct VISIBILITY_HIDDEN ARMAsmPrinter : public AsmPrinter {
47     ARMAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
48       : AsmPrinter(O, TM, T), DW(O, this, T), AFI(NULL), InCPMode(false) {
49       Subtarget = &TM.getSubtarget<ARMSubtarget>();
50     }
51
52     DwarfWriter DW;
53
54     /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
55     /// make the right decision when printing asm code for different targets.
56     const ARMSubtarget *Subtarget;
57
58     /// AFI - Keep a pointer to ARMFunctionInfo for the current
59     /// MachineFunction
60     ARMFunctionInfo *AFI;
61
62     /// We name each basic block in a Function with a unique number, so
63     /// that we can consistently refer to them later. This is cleared
64     /// at the beginning of each call to runOnMachineFunction().
65     ///
66     typedef std::map<const Value *, unsigned> ValueMapTy;
67     ValueMapTy NumberForBB;
68
69     /// Keeps the set of GlobalValues that require non-lazy-pointers for
70     /// indirect access.
71     std::set<std::string> GVNonLazyPtrs;
72
73     /// Keeps the set of external function GlobalAddresses that the asm
74     /// printer should generate stubs for.
75     std::set<std::string> FnStubs;
76
77     /// True if asm printer is printing a series of CONSTPOOL_ENTRY.
78     bool InCPMode;
79     
80     virtual const char *getPassName() const {
81       return "ARM Assembly Printer";
82     }
83
84     void printOperand(const MachineInstr *MI, int opNum,
85                       const char *Modifier = 0);
86     void printSOImmOperand(const MachineInstr *MI, int opNum);
87     void printSORegOperand(const MachineInstr *MI, int opNum);
88     void printAddrMode2Operand(const MachineInstr *MI, int OpNo);
89     void printAddrMode2OffsetOperand(const MachineInstr *MI, int OpNo);
90     void printAddrMode3Operand(const MachineInstr *MI, int OpNo);
91     void printAddrMode3OffsetOperand(const MachineInstr *MI, int OpNo);
92     void printAddrMode4Operand(const MachineInstr *MI, int OpNo,
93                                const char *Modifier = 0);
94     void printAddrMode5Operand(const MachineInstr *MI, int OpNo,
95                                const char *Modifier = 0);
96     void printAddrModePCOperand(const MachineInstr *MI, int OpNo,
97                                 const char *Modifier = 0);
98     void printThumbAddrModeRROperand(const MachineInstr *MI, int OpNo);
99     void printThumbAddrModeRI5Operand(const MachineInstr *MI, int OpNo,
100                                       unsigned Scale);
101     void printThumbAddrModeS1Operand(const MachineInstr *MI, int OpNo);
102     void printThumbAddrModeS2Operand(const MachineInstr *MI, int OpNo);
103     void printThumbAddrModeS4Operand(const MachineInstr *MI, int OpNo);
104     void printThumbAddrModeSPOperand(const MachineInstr *MI, int OpNo);
105     void printCCOperand(const MachineInstr *MI, int opNum);
106     void printPCLabel(const MachineInstr *MI, int opNum);
107     void printRegisterList(const MachineInstr *MI, int opNum);
108     void printCPInstOperand(const MachineInstr *MI, int opNum,
109                             const char *Modifier);
110     void printJTBlockOperand(const MachineInstr *MI, int opNum);
111
112     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
113                                  unsigned AsmVariant, const char *ExtraCode);
114
115     bool printInstruction(const MachineInstr *MI);  // autogenerated.
116     void printMachineInstruction(const MachineInstr *MI);
117     bool runOnMachineFunction(MachineFunction &F);
118     bool doInitialization(Module &M);
119     bool doFinalization(Module &M);
120
121     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
122       printDataDirective(MCPV->getType());
123
124       ARMConstantPoolValue *ACPV = (ARMConstantPoolValue*)MCPV;
125       std::string Name = Mang->getValueName(ACPV->getGV());
126       if (ACPV->isNonLazyPointer()) {
127         GVNonLazyPtrs.insert(Name);
128         O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
129       } else
130         O << Name;
131       if (ACPV->getPCAdjustment() != 0)
132         O << "-(" << TAI->getPrivateGlobalPrefix() << "PC"
133           << utostr(ACPV->getLabelId())
134           << "+" << (unsigned)ACPV->getPCAdjustment() << ")";
135       O << "\n";
136     }
137     
138     void getAnalysisUsage(AnalysisUsage &AU) const {
139       AU.setPreservesAll();
140       AU.addRequired<MachineDebugInfo>();
141     }
142   };
143 } // end of anonymous namespace
144
145 #include "ARMGenAsmWriter.inc"
146
147 /// createARMCodePrinterPass - Returns a pass that prints the ARM
148 /// assembly code for a MachineFunction to the given output stream,
149 /// using the given target machine description.  This should work
150 /// regardless of whether the function is in SSA form.
151 ///
152 FunctionPass *llvm::createARMCodePrinterPass(std::ostream &o,
153                                              ARMTargetMachine &tm) {
154   return new ARMAsmPrinter(o, tm, tm.getTargetAsmInfo());
155 }
156
157 /// runOnMachineFunction - This uses the printInstruction()
158 /// method to print assembly for each instruction.
159 ///
160 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
161   AFI = MF.getInfo<ARMFunctionInfo>();
162
163   if (Subtarget->isTargetDarwin()) {
164     DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
165   }
166
167   SetupMachineFunction(MF);
168   O << "\n";
169
170   // NOTE: we don't print out constant pools here, they are handled as
171   // instructions.
172
173   O << "\n";
174   // Print out labels for the function.
175   const Function *F = MF.getFunction();
176   switch (F->getLinkage()) {
177   default: assert(0 && "Unknown linkage type!");
178   case Function::InternalLinkage:
179     SwitchToTextSection("\t.text", F);
180     break;
181   case Function::ExternalLinkage:
182     SwitchToTextSection("\t.text", F);
183     O << "\t.globl\t" << CurrentFnName << "\n";
184     break;
185   case Function::WeakLinkage:
186   case Function::LinkOnceLinkage:
187     if (Subtarget->isTargetDarwin()) {
188       SwitchToTextSection(
189                 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
190       O << "\t.globl\t" << CurrentFnName << "\n";
191       O << "\t.weak_definition\t" << CurrentFnName << "\n";
192     } else {
193       O << TAI->getWeakRefDirective() << CurrentFnName << "\n";
194     }
195     break;
196   }
197
198   if (AFI->isThumbFunction()) {
199     EmitAlignment(1, F);
200     O << "\t.code\t16\n";
201     O << "\t.thumb_func\t" << CurrentFnName << "\n";
202     InCPMode = false;
203   } else
204     EmitAlignment(2, F);
205
206   O << CurrentFnName << ":\n";
207   if (Subtarget->isTargetDarwin()) {
208     // Emit pre-function debug information.
209     DW.BeginFunction(&MF);
210   }
211
212   // Print out code for the function.
213   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
214        I != E; ++I) {
215     // Print a label for the basic block.
216     if (I != MF.begin()) {
217       printBasicBlockLabel(I, true);
218       O << '\n';
219     }
220     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
221          II != E; ++II) {
222       // Print the assembly for the instruction.
223       printMachineInstruction(II);
224     }
225   }
226
227   if (TAI->hasDotTypeDotSizeDirective())
228     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
229
230   if (Subtarget->isTargetDarwin()) {
231     // Emit post-function debug information.
232     DW.EndFunction();
233   }
234
235   return false;
236 }
237
238 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
239                                  const char *Modifier) {
240   const MachineOperand &MO = MI->getOperand(opNum);
241   switch (MO.getType()) {
242   case MachineOperand::MO_Register:
243     if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
244       O << TM.getRegisterInfo()->get(MO.getReg()).Name;
245     else
246       assert(0 && "not implemented");
247     break;
248   case MachineOperand::MO_Immediate: {
249     if (!Modifier || strcmp(Modifier, "no_hash") != 0)
250       O << "#";
251
252     O << (int)MO.getImmedValue();
253     break;
254   }
255   case MachineOperand::MO_MachineBasicBlock:
256     printBasicBlockLabel(MO.getMachineBasicBlock());
257     return;
258   case MachineOperand::MO_GlobalAddress: {
259     bool isCallOp = Modifier && !strcmp(Modifier, "call");
260     GlobalValue *GV = MO.getGlobal();
261     std::string Name = Mang->getValueName(GV);
262     bool isExt = (GV->isExternal() || GV->hasWeakLinkage() ||
263                   GV->hasLinkOnceLinkage());
264     if (isExt && isCallOp && Subtarget->isTargetDarwin() &&
265         TM.getRelocationModel() != Reloc::Static) {
266       O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
267       FnStubs.insert(Name);
268     } else
269       O << Name;
270
271     if (GV->hasExternalWeakLinkage())
272       ExtWeakSymbols.insert(GV);
273     break;
274   }
275   case MachineOperand::MO_ExternalSymbol: {
276     bool isCallOp = Modifier && !strcmp(Modifier, "call");
277     std::string Name(TAI->getGlobalPrefix());
278     Name += MO.getSymbolName();
279     if (isCallOp && Subtarget->isTargetDarwin() &&
280         TM.getRelocationModel() != Reloc::Static) {
281       O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
282       FnStubs.insert(Name);
283     } else
284       O << Name;
285     break;
286   }
287   case MachineOperand::MO_ConstantPoolIndex:
288     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
289       << '_' << MO.getConstantPoolIndex();
290     break;
291   case MachineOperand::MO_JumpTableIndex:
292     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
293       << '_' << MO.getJumpTableIndex();
294     break;
295   default:
296     O << "<unknown operand type>"; abort (); break;
297   }
298 }
299
300 /// printSOImmOperand - SOImm is 4-bit rotate amount in bits 8-11 with 8-bit
301 /// immediate in bits 0-7.
302 void ARMAsmPrinter::printSOImmOperand(const MachineInstr *MI, int OpNum) {
303   const MachineOperand &MO = MI->getOperand(OpNum);
304   assert(MO.isImmediate() && (MO.getImmedValue() < (1 << 12)) &&
305          "Not a valid so_imm value!");
306   unsigned Imm = ARM_AM::getSOImmValImm(MO.getImmedValue());
307   unsigned Rot = ARM_AM::getSOImmValRot(MO.getImmedValue());
308   
309   // Print low-level immediate formation info, per
310   // A5.1.3: "Data-processing operands - Immediate".
311   if (Rot) {
312     O << "#" << Imm << ", " << Rot;
313     // Pretty printed version.
314     O << ' ' << TAI->getCommentString() << ' ' << (int)ARM_AM::rotr32(Imm, Rot);
315   } else {
316     O << "#" << Imm;
317   }
318 }
319
320 // so_reg is a 4-operand unit corresponding to register forms of the A5.1
321 // "Addressing Mode 1 - Data-processing operands" forms.  This includes:
322 //    REG 0   0    - e.g. R5
323 //    REG REG 0,SH_OPC     - e.g. R5, ROR R3
324 //    REG 0   IMM,SH_OPC  - e.g. R5, LSL #3
325 void ARMAsmPrinter::printSORegOperand(const MachineInstr *MI, int Op) {
326   const MachineOperand &MO1 = MI->getOperand(Op);
327   const MachineOperand &MO2 = MI->getOperand(Op+1);
328   const MachineOperand &MO3 = MI->getOperand(Op+2);
329
330   assert(MRegisterInfo::isPhysicalRegister(MO1.getReg()));
331   O << TM.getRegisterInfo()->get(MO1.getReg()).Name;
332
333   // Print the shift opc.
334   O << ", "
335     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO3.getImmedValue()))
336     << " ";
337
338   if (MO2.getReg()) {
339     assert(MRegisterInfo::isPhysicalRegister(MO2.getReg()));
340     O << TM.getRegisterInfo()->get(MO2.getReg()).Name;
341     assert(ARM_AM::getSORegOffset(MO3.getImm()) == 0);
342   } else {
343     O << "#" << ARM_AM::getSORegOffset(MO3.getImm());
344   }
345 }
346
347 void ARMAsmPrinter::printAddrMode2Operand(const MachineInstr *MI, int Op) {
348   const MachineOperand &MO1 = MI->getOperand(Op);
349   const MachineOperand &MO2 = MI->getOperand(Op+1);
350   const MachineOperand &MO3 = MI->getOperand(Op+2);
351
352   if (!MO1.isRegister()) {   // FIXME: This is for CP entries, but isn't right.
353     printOperand(MI, Op);
354     return;
355   }
356
357   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).Name;
358
359   if (!MO2.getReg()) {
360     if (ARM_AM::getAM2Offset(MO3.getImm()))  // Don't print +0.
361       O << ", #"
362         << (char)ARM_AM::getAM2Op(MO3.getImm())
363         << ARM_AM::getAM2Offset(MO3.getImm());
364     O << "]";
365     return;
366   }
367
368   O << ", "
369     << (char)ARM_AM::getAM2Op(MO3.getImm())
370     << TM.getRegisterInfo()->get(MO2.getReg()).Name;
371   
372   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm()))
373     O << ", "
374       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO3.getImmedValue()))
375       << " #" << ShImm;
376   O << "]";
377 }
378
379 void ARMAsmPrinter::printAddrMode2OffsetOperand(const MachineInstr *MI, int Op){
380   const MachineOperand &MO1 = MI->getOperand(Op);
381   const MachineOperand &MO2 = MI->getOperand(Op+1);
382
383   if (!MO1.getReg()) {
384     if (ARM_AM::getAM2Offset(MO2.getImm()))  // Don't print +0.
385       O << "#"
386         << (char)ARM_AM::getAM2Op(MO2.getImm())
387         << ARM_AM::getAM2Offset(MO2.getImm());
388     return;
389   }
390
391   O << (char)ARM_AM::getAM2Op(MO2.getImm())
392     << TM.getRegisterInfo()->get(MO1.getReg()).Name;
393   
394   if (unsigned ShImm = ARM_AM::getAM2Offset(MO2.getImm()))
395     O << ", "
396       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO2.getImmedValue()))
397       << " #" << ShImm;
398 }
399
400 void ARMAsmPrinter::printAddrMode3Operand(const MachineInstr *MI, int Op) {
401   const MachineOperand &MO1 = MI->getOperand(Op);
402   const MachineOperand &MO2 = MI->getOperand(Op+1);
403   const MachineOperand &MO3 = MI->getOperand(Op+2);
404   
405   assert(MRegisterInfo::isPhysicalRegister(MO1.getReg()));
406   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).Name;
407
408   if (MO2.getReg()) {
409     O << ", "
410       << (char)ARM_AM::getAM3Op(MO3.getImm())
411       << TM.getRegisterInfo()->get(MO2.getReg()).Name
412       << "]";
413     return;
414   }
415   
416   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm()))
417     O << ", #"
418       << (char)ARM_AM::getAM3Op(MO3.getImm())
419       << ImmOffs;
420   O << "]";
421 }
422
423 void ARMAsmPrinter::printAddrMode3OffsetOperand(const MachineInstr *MI, int Op){
424   const MachineOperand &MO1 = MI->getOperand(Op);
425   const MachineOperand &MO2 = MI->getOperand(Op+1);
426
427   if (MO1.getReg()) {
428     O << (char)ARM_AM::getAM3Op(MO2.getImm())
429       << TM.getRegisterInfo()->get(MO1.getReg()).Name;
430     return;
431   }
432
433   unsigned ImmOffs = ARM_AM::getAM3Offset(MO2.getImm());
434   O << "#"
435   << (char)ARM_AM::getAM3Op(MO2.getImm())
436     << ImmOffs;
437 }
438   
439 void ARMAsmPrinter::printAddrMode4Operand(const MachineInstr *MI, int Op,
440                                           const char *Modifier) {
441   const MachineOperand &MO1 = MI->getOperand(Op);
442   const MachineOperand &MO2 = MI->getOperand(Op+1);
443   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
444   if (Modifier && strcmp(Modifier, "submode") == 0) {
445     if (MO1.getReg() == ARM::SP) {
446       bool isLDM = (MI->getOpcode() == ARM::LDM ||
447                     MI->getOpcode() == ARM::LDM_RET);
448       O << ARM_AM::getAMSubModeAltStr(Mode, isLDM);
449     } else
450       O << ARM_AM::getAMSubModeStr(Mode);
451   } else {
452     printOperand(MI, Op);
453     if (ARM_AM::getAM4WBFlag(MO2.getImm()))
454       O << "!";
455   }
456 }
457
458 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
459                                           const char *Modifier) {
460   const MachineOperand &MO1 = MI->getOperand(Op);
461   const MachineOperand &MO2 = MI->getOperand(Op+1);
462
463   if (!MO1.isRegister()) {   // FIXME: This is for CP entries, but isn't right.
464     printOperand(MI, Op);
465     return;
466   }
467   
468   assert(MRegisterInfo::isPhysicalRegister(MO1.getReg()));
469
470   if (Modifier && strcmp(Modifier, "submode") == 0) {
471     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
472     if (MO1.getReg() == ARM::SP) {
473       bool isFLDM = (MI->getOpcode() == ARM::FLDMD ||
474                      MI->getOpcode() == ARM::FLDMS);
475       O << ARM_AM::getAMSubModeAltStr(Mode, isFLDM);
476     } else
477       O << ARM_AM::getAMSubModeStr(Mode);
478     return;
479   } else if (Modifier && strcmp(Modifier, "base") == 0) {
480     // Used for FSTM{D|S} and LSTM{D|S} operations.
481     O << TM.getRegisterInfo()->get(MO1.getReg()).Name;
482     if (ARM_AM::getAM5WBFlag(MO2.getImm()))
483       O << "!";
484     return;
485   }
486   
487   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).Name;
488   
489   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
490     O << ", #"
491       << (char)ARM_AM::getAM5Op(MO2.getImm())
492       << ImmOffs*4;
493   }
494   O << "]";
495 }
496
497 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
498                                            const char *Modifier) {
499   if (Modifier && strcmp(Modifier, "label") == 0) {
500     printPCLabel(MI, Op+1);
501     return;
502   }
503
504   const MachineOperand &MO1 = MI->getOperand(Op);
505   assert(MRegisterInfo::isPhysicalRegister(MO1.getReg()));
506   O << "[pc, +" << TM.getRegisterInfo()->get(MO1.getReg()).Name << "]";
507 }
508
509 void
510 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op) {
511   const MachineOperand &MO1 = MI->getOperand(Op);
512   const MachineOperand &MO2 = MI->getOperand(Op+1);
513   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).Name;
514   O << ", " << TM.getRegisterInfo()->get(MO2.getReg()).Name << "]";
515 }
516
517 void
518 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
519                                             unsigned Scale) {
520   const MachineOperand &MO1 = MI->getOperand(Op);
521   const MachineOperand &MO2 = MI->getOperand(Op+2);
522
523   if (!MO1.isRegister()) {   // FIXME: This is for CP entries, but isn't right.
524     printOperand(MI, Op);
525     return;
526   }
527
528   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).Name;
529   if (unsigned ImmOffs = MO2.getImm()) {
530     O << ", #" << ImmOffs;
531     if (Scale > 1)
532       O << " * " << Scale;
533   }
534   O << "]";
535 }
536
537 void
538 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op) {
539   if (MI->getOperand(Op+1).getReg())
540     printThumbAddrModeRROperand(MI, Op);
541   else
542     printThumbAddrModeRI5Operand(MI, Op, 1);
543 }
544 void
545 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op) {
546   if (MI->getOperand(Op+1).getReg())
547     printThumbAddrModeRROperand(MI, Op);
548   else
549     printThumbAddrModeRI5Operand(MI, Op, 2);
550 }
551 void
552 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op) {
553   if (MI->getOperand(Op+1).getReg())
554     printThumbAddrModeRROperand(MI, Op);
555   else
556     printThumbAddrModeRI5Operand(MI, Op, 4);
557 }
558
559 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op) {
560   const MachineOperand &MO1 = MI->getOperand(Op);
561   const MachineOperand &MO2 = MI->getOperand(Op+1);
562   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).Name;
563   if (unsigned ImmOffs = MO2.getImm())
564     O << ", #" << ImmOffs << " * 4";
565   O << "]";
566 }
567
568 void ARMAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
569   int CC = (int)MI->getOperand(opNum).getImmedValue();
570   O << ARMCondCodeToString((ARMCC::CondCodes)CC);
571 }
572
573 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int opNum) {
574   int Id = (int)MI->getOperand(opNum).getImmedValue();
575   O << TAI->getPrivateGlobalPrefix() << "PC" << Id;
576 }
577
578 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int opNum) {
579   O << "{";
580   for (unsigned i = opNum, e = MI->getNumOperands(); i != e; ++i) {
581     printOperand(MI, i);
582     if (i != e-1) O << ", ";
583   }
584   O << "}";
585 }
586
587 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNo,
588                                        const char *Modifier) {
589   assert(Modifier && "This operand only works with a modifier!");
590   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
591   // data itself.
592   if (!strcmp(Modifier, "label")) {
593     unsigned ID = MI->getOperand(OpNo).getImm();
594     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
595       << '_' << ID << ":\n";
596   } else {
597     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
598     unsigned CPI = MI->getOperand(OpNo).getConstantPoolIndex();
599
600     const MachineConstantPoolEntry &MCPE =  // Chasing pointers is fun?
601       MI->getParent()->getParent()->getConstantPool()->getConstants()[CPI];
602     
603     if (MCPE.isMachineConstantPoolEntry())
604       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
605     else
606       EmitGlobalConstant(MCPE.Val.ConstVal);
607   }
608 }
609
610 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNo) {
611   const MachineOperand &MO1 = MI->getOperand(OpNo);
612   const MachineOperand &MO2 = MI->getOperand(OpNo+1); // Unique Id
613   unsigned JTI = MO1.getJumpTableIndex();
614   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
615     << '_' << JTI << '_' << MO2.getImmedValue() << ":\n";
616
617   const char *JTEntryDirective = TAI->getJumpTableDirective();
618   if (!JTEntryDirective)
619     JTEntryDirective = TAI->getData32bitsDirective();
620
621   const MachineFunction *MF = MI->getParent()->getParent();
622   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
623   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
624   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
625   bool UseSet= TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
626   std::set<MachineBasicBlock*> JTSets;
627   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
628     MachineBasicBlock *MBB = JTBBs[i];
629     if (UseSet && JTSets.insert(MBB).second)
630       printSetLabel(JTI, MO2.getImmedValue(), MBB);
631
632     O << JTEntryDirective << ' ';
633     if (UseSet)
634       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
635         << '_' << JTI << '_' << MO2.getImmedValue()
636         << "_set_" << MBB->getNumber();
637     else if (TM.getRelocationModel() == Reloc::PIC_) {
638       printBasicBlockLabel(MBB, false, false);
639       // If the arch uses custom Jump Table directives, don't calc relative to JT
640       if (!TAI->getJumpTableDirective()) 
641         O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
642           << getFunctionNumber() << '_' << JTI << '_' << MO2.getImmedValue();
643     } else
644       printBasicBlockLabel(MBB, false, false);
645     O << '\n';
646   }
647 }
648
649
650 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
651                                     unsigned AsmVariant, const char *ExtraCode){
652   // Does this asm operand have a single letter operand modifier?
653   if (ExtraCode && ExtraCode[0]) {
654     if (ExtraCode[1] != 0) return true; // Unknown modifier.
655     
656     switch (ExtraCode[0]) {
657     default: return true;  // Unknown modifier.
658     case 'Q':
659       if (TM.getTargetData()->isLittleEndian())
660         break;
661       // Fallthrough
662     case 'R':
663       if (TM.getTargetData()->isBigEndian())
664         break;
665       // Fallthrough
666     case 'H': // Write second word of DI / DF reference.  
667       // Verify that this operand has two consecutive registers.
668       if (!MI->getOperand(OpNo).isRegister() ||
669           OpNo+1 == MI->getNumOperands() ||
670           !MI->getOperand(OpNo+1).isRegister())
671         return true;
672       ++OpNo;   // Return the high-part.
673     }
674   }
675   
676   printOperand(MI, OpNo);
677   return false;
678 }
679
680 void ARMAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
681   ++EmittedInsts;
682
683   if (MI->getOpcode() == ARM::CONSTPOOL_ENTRY) {
684     if (!InCPMode && AFI->isThumbFunction()) {
685       EmitAlignment(2);
686       InCPMode = true;
687     }
688   } else {
689     if (InCPMode && AFI->isThumbFunction()) {
690       EmitAlignment(1);
691       InCPMode = false;
692     }
693     O << "\t";
694   }
695
696   // Call the autogenerated instruction printer routines.
697   printInstruction(MI);
698 }
699
700 bool ARMAsmPrinter::doInitialization(Module &M) {
701   if (Subtarget->isTargetDarwin()) {
702     // Emit initial debug information.
703     DW.BeginModule(&M);
704   }
705   
706   return AsmPrinter::doInitialization(M);
707 }
708
709 bool ARMAsmPrinter::doFinalization(Module &M) {
710   const TargetData *TD = TM.getTargetData();
711
712   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
713        I != E; ++I) {
714     if (!I->hasInitializer())   // External global require no code
715       continue;
716
717     if (EmitSpecialLLVMGlobal(I))
718       continue;
719
720     std::string name = Mang->getValueName(I);
721     Constant *C = I->getInitializer();
722     unsigned Size = TD->getTypeSize(C->getType());
723     unsigned Align = TD->getPreferredAlignmentLog(I);
724
725     if (I->hasHiddenVisibility())
726       if (const char *Directive = TAI->getHiddenDirective())
727         O << Directive << name << "\n";
728     if (Subtarget->isTargetELF())
729       O << "\t.type " << name << ",@object\n";
730     
731     if (C->isNullValue()) {
732       if (I->hasExternalLinkage()) {
733         if (const char *Directive = TAI->getZeroFillDirective()) {
734           O << "\t.globl\t" << name << "\n";
735           O << Directive << "__DATA__, __common, " << name << ", "
736             << Size << ", " << Align << "\n";
737           continue;
738         }
739       }
740
741       if (!I->hasSection() &&
742           (I->hasInternalLinkage() || I->hasWeakLinkage() ||
743            I->hasLinkOnceLinkage())) {
744         if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
745         if (!NoZerosInBSS && TAI->getBSSSection())
746           SwitchToDataSection(TAI->getBSSSection(), I);
747         else
748           SwitchToDataSection(TAI->getDataSection(), I);
749         if (TAI->getLCOMMDirective() != NULL) {
750           if (I->hasInternalLinkage()) {
751             O << TAI->getLCOMMDirective() << name << "," << Size;
752             if (Subtarget->isTargetDarwin())
753               O << "," << Align;
754           } else
755             O << TAI->getCOMMDirective()  << name << "," << Size;
756         } else {
757           if (I->hasInternalLinkage())
758             O << "\t.local\t" << name << "\n";
759           O << TAI->getCOMMDirective()  << name << "," << Size;
760           if (TAI->getCOMMDirectiveTakesAlignment())
761             O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
762         }
763         O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
764         continue;
765       }
766     }
767
768     switch (I->getLinkage()) {
769     case GlobalValue::LinkOnceLinkage:
770     case GlobalValue::WeakLinkage:
771       if (Subtarget->isTargetDarwin()) {
772         O << "\t.globl " << name << "\n"
773           << "\t.weak_definition " << name << "\n";
774         SwitchToDataSection("\t.section __DATA,__const_coal,coalesced", I);
775       } else {
776         std::string SectionName("\t.section\t.llvm.linkonce.d." +
777                                 name +
778                                 ",\"aw\",%progbits");
779         SwitchToDataSection(SectionName.c_str(), I);
780         O << "\t.weak " << name << "\n";
781       }
782       break;
783     case GlobalValue::AppendingLinkage:
784       // FIXME: appending linkage variables should go into a section of
785       // their name or something.  For now, just emit them as external.
786     case GlobalValue::ExternalLinkage:
787       O << "\t.globl " << name << "\n";
788       // FALL THROUGH
789     case GlobalValue::InternalLinkage: {
790       if (I->isConstant()) {
791         const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
792         if (TAI->getCStringSection() && CVA && CVA->isCString()) {
793           SwitchToDataSection(TAI->getCStringSection(), I);
794           break;
795         }
796       }
797       // FIXME: special handling for ".ctors" & ".dtors" sections
798       if (I->hasSection() &&
799           (I->getSection() == ".ctors" ||
800            I->getSection() == ".dtors")) {
801         assert(!Subtarget->isTargetDarwin());
802         std::string SectionName = ".section " + I->getSection();
803         SectionName += ",\"aw\",%progbits";
804         SwitchToDataSection(SectionName.c_str());
805       } else {
806         if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
807           SwitchToDataSection(TAI->getBSSSection(), I);
808         else
809           SwitchToDataSection(TAI->getDataSection(), I);
810       }
811
812       break;
813     }
814     default:
815       assert(0 && "Unknown linkage type!");
816       break;
817     }
818
819     EmitAlignment(Align, I);
820     O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
821       << "\n";
822     if (TAI->hasDotTypeDotSizeDirective())
823       O << "\t.size " << name << ", " << Size << "\n";
824     // If the initializer is a extern weak symbol, remember to emit the weak
825     // reference!
826     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
827       if (GV->hasExternalWeakLinkage())
828       ExtWeakSymbols.insert(GV);
829
830     EmitGlobalConstant(C);
831     O << '\n';
832   }
833
834   if (Subtarget->isTargetDarwin()) {
835     SwitchToDataSection("");
836
837     // Output stubs for dynamically-linked functions
838     unsigned j = 1;
839     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
840          i != e; ++i, ++j) {
841       if (TM.getRelocationModel() == Reloc::PIC_)
842         SwitchToTextSection(".section __TEXT,__picsymbolstub4,symbol_stubs,"
843                             "none,16", 0);
844       else
845         SwitchToTextSection(".section __TEXT,__symbol_stub4,symbol_stubs,"
846                             "none,12", 0);
847
848       EmitAlignment(2);
849       O << "\t.code\t32\n";
850
851       O << "L" << *i << "$stub:\n";
852       O << "\t.indirect_symbol " << *i << "\n";
853       O << "\tldr ip, L" << *i << "$slp\n";
854       if (TM.getRelocationModel() == Reloc::PIC_) {
855         O << "L" << *i << "$scv:\n";
856         O << "\tadd ip, pc, ip\n";
857       }
858       O << "\tldr pc, [ip, #0]\n";
859       O << "L" << *i << "$slp:\n";
860       if (TM.getRelocationModel() == Reloc::PIC_)
861         O << "\t.long\tL" << *i << "$lazy_ptr-(L" << *i << "$scv+8)\n";
862       else
863         O << "\t.long\tL" << *i << "$lazy_ptr\n";
864       SwitchToDataSection(".lazy_symbol_pointer", 0);
865       O << "L" << *i << "$lazy_ptr:\n";
866       O << "\t.indirect_symbol " << *i << "\n";
867       O << "\t.long\tdyld_stub_binding_helper\n";
868     }
869     O << "\n";
870
871     // Output non-lazy-pointers for external and common global variables.
872     if (GVNonLazyPtrs.begin() != GVNonLazyPtrs.end())
873       SwitchToDataSection(".non_lazy_symbol_pointer", 0);
874     for (std::set<std::string>::iterator i = GVNonLazyPtrs.begin(),
875            e = GVNonLazyPtrs.end(); i != e; ++i) {
876       O << "L" << *i << "$non_lazy_ptr:\n";
877       O << "\t.indirect_symbol " << *i << "\n";
878       O << "\t.long\t0\n";
879     }
880
881     // Emit initial debug information.
882     DW.EndModule();
883
884     // Funny Darwin hack: This flag tells the linker that no global symbols
885     // contain code that falls through to other global symbols (e.g. the obvious
886     // implementation of multiple entry points).  If this doesn't occur, the
887     // linker can safely perform dead code stripping.  Since LLVM never
888     // generates code that does this, it is always safe to set.
889     O << "\t.subsections_via_symbols\n";
890   }
891
892   AsmPrinter::doFinalization(M);
893   return false; // success
894 }