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