LLVM API Documentation

LLParser.h
Go to the documentation of this file.
00001 //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the parser class for .ll files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_ASMPARSER_LLPARSER_H
00015 #define LLVM_ASMPARSER_LLPARSER_H
00016 
00017 #include "LLLexer.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/StringMap.h"
00020 #include "llvm/IR/Attributes.h"
00021 #include "llvm/IR/Instructions.h"
00022 #include "llvm/IR/Module.h"
00023 #include "llvm/IR/Operator.h"
00024 #include "llvm/IR/Type.h"
00025 #include "llvm/Support/ValueHandle.h"
00026 #include <map>
00027 
00028 namespace llvm {
00029   class Module;
00030   class OpaqueType;
00031   class Function;
00032   class Value;
00033   class BasicBlock;
00034   class Instruction;
00035   class Constant;
00036   class GlobalValue;
00037   class MDString;
00038   class MDNode;
00039   class StructType;
00040 
00041   /// ValID - Represents a reference of a definition of some sort with no type.
00042   /// There are several cases where we have to parse the value but where the
00043   /// type can depend on later context.  This may either be a numeric reference
00044   /// or a symbolic (%var) reference.  This is just a discriminated union.
00045   struct ValID {
00046     enum {
00047       t_LocalID, t_GlobalID,      // ID in UIntVal.
00048       t_LocalName, t_GlobalName,  // Name in StrVal.
00049       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
00050       t_Null, t_Undef, t_Zero,    // No value.
00051       t_EmptyArray,               // No value:  []
00052       t_Constant,                 // Value in ConstantVal.
00053       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
00054       t_MDNode,                   // Value in MDNodeVal.
00055       t_MDString,                 // Value in MDStringVal.
00056       t_ConstantStruct,           // Value in ConstantStructElts.
00057       t_PackedConstantStruct      // Value in ConstantStructElts.
00058     } Kind;
00059 
00060     LLLexer::LocTy Loc;
00061     unsigned UIntVal;
00062     std::string StrVal, StrVal2;
00063     APSInt APSIntVal;
00064     APFloat APFloatVal;
00065     Constant *ConstantVal;
00066     MDNode *MDNodeVal;
00067     MDString *MDStringVal;
00068     Constant **ConstantStructElts;
00069 
00070     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
00071     ~ValID() {
00072       if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
00073         delete [] ConstantStructElts;
00074     }
00075 
00076     bool operator<(const ValID &RHS) const {
00077       if (Kind == t_LocalID || Kind == t_GlobalID)
00078         return UIntVal < RHS.UIntVal;
00079       assert((Kind == t_LocalName || Kind == t_GlobalName ||
00080               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
00081              "Ordering not defined for this ValID kind yet");
00082       return StrVal < RHS.StrVal;
00083     }
00084   };
00085 
00086   class LLParser {
00087   public:
00088     typedef LLLexer::LocTy LocTy;
00089   private:
00090     LLVMContext &Context;
00091     LLLexer Lex;
00092     Module *M;
00093 
00094     // Instruction metadata resolution.  Each instruction can have a list of
00095     // MDRef info associated with them.
00096     //
00097     // The simpler approach of just creating temporary MDNodes and then calling
00098     // RAUW on them when the definition is processed doesn't work because some
00099     // instruction metadata kinds, such as dbg, get stored in the IR in an
00100     // "optimized" format which doesn't participate in the normal value use
00101     // lists. This means that RAUW doesn't work, even on temporary MDNodes
00102     // which otherwise support RAUW. Instead, we defer resolving MDNode
00103     // references until the definitions have been processed.
00104     struct MDRef {
00105       SMLoc Loc;
00106       unsigned MDKind, MDSlot;
00107     };
00108     DenseMap<Instruction*, std::vector<MDRef> > ForwardRefInstMetadata;
00109 
00110     // Type resolution handling data structures.  The location is set when we
00111     // have processed a use of the type but not a definition yet.
00112     StringMap<std::pair<Type*, LocTy> > NamedTypes;
00113     std::vector<std::pair<Type*, LocTy> > NumberedTypes;
00114 
00115     std::vector<TrackingVH<MDNode> > NumberedMetadata;
00116     std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> > ForwardRefMDNodes;
00117 
00118     // Global Value reference information.
00119     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
00120     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
00121     std::vector<GlobalValue*> NumberedVals;
00122 
00123     // References to blockaddress.  The key is the function ValID, the value is
00124     // a list of references to blocks in that function.
00125     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >
00126       ForwardRefBlockAddresses;
00127 
00128     // Attribute builder reference information.
00129     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
00130     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
00131 
00132   public:
00133     LLParser(MemoryBuffer *F, SourceMgr &SM, SMDiagnostic &Err, Module *m) :
00134       Context(m->getContext()), Lex(F, SM, Err, m->getContext()),
00135       M(m) {}
00136     bool Run();
00137 
00138     LLVMContext &getContext() { return Context; }
00139 
00140   private:
00141 
00142     bool Error(LocTy L, const Twine &Msg) const {
00143       return Lex.Error(L, Msg);
00144     }
00145     bool TokError(const Twine &Msg) const {
00146       return Error(Lex.getLoc(), Msg);
00147     }
00148 
00149     /// GetGlobalVal - Get a value with the specified name or ID, creating a
00150     /// forward reference record if needed.  This can return null if the value
00151     /// exists but does not have the right type.
00152     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
00153     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
00154 
00155     // Helper Routines.
00156     bool ParseToken(lltok::Kind T, const char *ErrMsg);
00157     bool EatIfPresent(lltok::Kind T) {
00158       if (Lex.getKind() != T) return false;
00159       Lex.Lex();
00160       return true;
00161     }
00162 
00163     FastMathFlags EatFastMathFlagsIfPresent() {
00164       FastMathFlags FMF;
00165       while (true)
00166         switch (Lex.getKind()) {
00167         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
00168         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
00169         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
00170         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
00171         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
00172         default: return FMF;
00173         }
00174       return FMF;
00175     }
00176 
00177     bool ParseOptionalToken(lltok::Kind T, bool &Present, LocTy *Loc = 0) {
00178       if (Lex.getKind() != T) {
00179         Present = false;
00180       } else {
00181         if (Loc)
00182           *Loc = Lex.getLoc();
00183         Lex.Lex();
00184         Present = true;
00185       }
00186       return false;
00187     }
00188     bool ParseStringConstant(std::string &Result);
00189     bool ParseUInt32(unsigned &Val);
00190     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
00191       Loc = Lex.getLoc();
00192       return ParseUInt32(Val);
00193     }
00194 
00195     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
00196     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
00197     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
00198     bool ParseOptionalParamAttrs(AttrBuilder &B);
00199     bool ParseOptionalReturnAttrs(AttrBuilder &B);
00200     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
00201     bool ParseOptionalLinkage(unsigned &Linkage) {
00202       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
00203     }
00204     bool ParseOptionalVisibility(unsigned &Visibility);
00205     bool ParseOptionalCallingConv(CallingConv::ID &CC);
00206     bool ParseOptionalAlignment(unsigned &Alignment);
00207     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
00208                                AtomicOrdering &Ordering);
00209     bool ParseOptionalStackAlignment(unsigned &Alignment);
00210     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
00211     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
00212     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
00213       bool AteExtraComma;
00214       if (ParseIndexList(Indices, AteExtraComma)) return true;
00215       if (AteExtraComma)
00216         return TokError("expected index");
00217       return false;
00218     }
00219 
00220     // Top-Level Entities
00221     bool ParseTopLevelEntities();
00222     bool ValidateEndOfModule();
00223     bool ParseTargetDefinition();
00224     bool ParseModuleAsm();
00225     bool ParseDepLibs();        // FIXME: Remove in 4.0.
00226     bool ParseUnnamedType();
00227     bool ParseNamedType();
00228     bool ParseDeclare();
00229     bool ParseDefine();
00230 
00231     bool ParseGlobalType(bool &IsConstant);
00232     bool ParseUnnamedGlobal();
00233     bool ParseNamedGlobal();
00234     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
00235                      bool HasLinkage, unsigned Visibility);
00236     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility);
00237     bool ParseStandaloneMetadata();
00238     bool ParseNamedMetadata();
00239     bool ParseMDString(MDString *&Result);
00240     bool ParseMDNodeID(MDNode *&Result);
00241     bool ParseMDNodeID(MDNode *&Result, unsigned &SlotNo);
00242     bool ParseUnnamedAttrGrp();
00243     bool ParseFnAttributeValuePairs(AttrBuilder &B,
00244                                     std::vector<unsigned> &FwdRefAttrGrps,
00245                                     bool inAttrGrp, LocTy &NoBuiltinLoc);
00246 
00247     // Type Parsing.
00248     bool ParseType(Type *&Result, bool AllowVoid = false);
00249     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
00250       Loc = Lex.getLoc();
00251       return ParseType(Result, AllowVoid);
00252     }
00253     bool ParseAnonStructType(Type *&Result, bool Packed);
00254     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
00255     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
00256                                std::pair<Type*, LocTy> &Entry,
00257                                Type *&ResultTy);
00258 
00259     bool ParseArrayVectorType(Type *&Result, bool isVector);
00260     bool ParseFunctionType(Type *&Result);
00261 
00262     // Function Semantic Analysis.
00263     class PerFunctionState {
00264       LLParser &P;
00265       Function &F;
00266       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
00267       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
00268       std::vector<Value*> NumberedVals;
00269 
00270       /// FunctionNumber - If this is an unnamed function, this is the slot
00271       /// number of it, otherwise it is -1.
00272       int FunctionNumber;
00273     public:
00274       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
00275       ~PerFunctionState();
00276 
00277       Function &getFunction() const { return F; }
00278 
00279       bool FinishFunction();
00280 
00281       /// GetVal - Get a value with the specified name or ID, creating a
00282       /// forward reference record if needed.  This can return null if the value
00283       /// exists but does not have the right type.
00284       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
00285       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
00286 
00287       /// SetInstName - After an instruction is parsed and inserted into its
00288       /// basic block, this installs its name.
00289       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
00290                        Instruction *Inst);
00291 
00292       /// GetBB - Get a basic block with the specified name or ID, creating a
00293       /// forward reference record if needed.  This can return null if the value
00294       /// is not a BasicBlock.
00295       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
00296       BasicBlock *GetBB(unsigned ID, LocTy Loc);
00297 
00298       /// DefineBB - Define the specified basic block, which is either named or
00299       /// unnamed.  If there is an error, this returns null otherwise it returns
00300       /// the block being defined.
00301       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
00302     };
00303 
00304     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
00305                              PerFunctionState *PFS);
00306 
00307     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
00308     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
00309       return ParseValue(Ty, V, &PFS);
00310     }
00311     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
00312                     PerFunctionState &PFS) {
00313       Loc = Lex.getLoc();
00314       return ParseValue(Ty, V, &PFS);
00315     }
00316 
00317     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
00318     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
00319       return ParseTypeAndValue(V, &PFS);
00320     }
00321     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
00322       Loc = Lex.getLoc();
00323       return ParseTypeAndValue(V, PFS);
00324     }
00325     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
00326                                 PerFunctionState &PFS);
00327     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
00328       LocTy Loc;
00329       return ParseTypeAndBasicBlock(BB, Loc, PFS);
00330     }
00331 
00332 
00333     struct ParamInfo {
00334       LocTy Loc;
00335       Value *V;
00336       AttributeSet Attrs;
00337       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
00338         : Loc(loc), V(v), Attrs(attrs) {}
00339     };
00340     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
00341                             PerFunctionState &PFS);
00342 
00343     // Constant Parsing.
00344     bool ParseValID(ValID &ID, PerFunctionState *PFS = NULL);
00345     bool ParseGlobalValue(Type *Ty, Constant *&V);
00346     bool ParseGlobalTypeAndValue(Constant *&V);
00347     bool ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts);
00348     bool ParseMetadataListValue(ValID &ID, PerFunctionState *PFS);
00349     bool ParseMetadataValue(ValID &ID, PerFunctionState *PFS);
00350     bool ParseMDNodeVector(SmallVectorImpl<Value*> &, PerFunctionState *PFS);
00351     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
00352 
00353     // Function Parsing.
00354     struct ArgInfo {
00355       LocTy Loc;
00356       Type *Ty;
00357       AttributeSet Attrs;
00358       std::string Name;
00359       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
00360         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
00361     };
00362     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
00363     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
00364     bool ParseFunctionBody(Function &Fn);
00365     bool ParseBasicBlock(PerFunctionState &PFS);
00366 
00367     // Instruction Parsing.  Each instruction parsing routine can return with a
00368     // normal result, an error result, or return having eaten an extra comma.
00369     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
00370     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
00371                          PerFunctionState &PFS);
00372     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
00373 
00374     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
00375     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
00376     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
00377     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
00378     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
00379     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
00380 
00381     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
00382                          unsigned OperandType);
00383     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
00384     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
00385     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
00386     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
00387     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
00388     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
00389     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
00390     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
00391     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
00392     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
00393     bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail);
00394     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
00395     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
00396     int ParseStore(Instruction *&I, PerFunctionState &PFS);
00397     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
00398     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
00399     int ParseFence(Instruction *&I, PerFunctionState &PFS);
00400     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
00401     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
00402     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
00403 
00404     bool ResolveForwardRefBlockAddresses(Function *TheFn,
00405                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
00406                                          PerFunctionState *PFS);
00407   };
00408 } // End llvm namespace
00409 
00410 #endif