1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 coordinates the per-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGDebugInfo.h" 15 #include "CodeGenModule.h" 16 #include "CodeGenFunction.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/Basic/Diagnostic.h" 20 #include "clang/Basic/LangOptions.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Basic/TargetInfo.h" 23 #include "llvm/CallingConv.h" 24 #include "llvm/Constants.h" 25 #include "llvm/DerivedTypes.h" 26 #include "llvm/Module.h" 27 #include "llvm/Intrinsics.h" 28 #include "llvm/Analysis/Verifier.h" 29 #include <algorithm> 30 using namespace clang; 31 using namespace CodeGen; 32 33 34 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 35 llvm::Module &M, const llvm::TargetData &TD, 36 Diagnostic &diags, bool GenerateDebugInfo) 37 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags), 38 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0), 39 CFConstantStringClassRef(0) { 40 //TODO: Make this selectable at runtime 41 Runtime = CreateObjCRuntime(M, 42 getTypes().ConvertType(getContext().IntTy), 43 getTypes().ConvertType(getContext().LongTy)); 44 45 // If debug info generation is enabled, create the CGDebugInfo object. 46 if (GenerateDebugInfo) 47 DebugInfo = new CGDebugInfo(this); 48 else 49 DebugInfo = NULL; 50 } 51 52 CodeGenModule::~CodeGenModule() { 53 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction(); 54 if (ObjCInitFunction) 55 AddGlobalCtor(ObjCInitFunction); 56 EmitStatics(); 57 EmitGlobalCtors(); 58 EmitAnnotations(); 59 delete Runtime; 60 delete DebugInfo; 61 // Run the verifier to check that the generated code is consistent. 62 assert(!verifyModule(TheModule)); 63 } 64 65 /// WarnUnsupported - Print out a warning that codegen doesn't support the 66 /// specified stmt yet. 67 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) { 68 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 69 "cannot codegen this %0 yet"); 70 SourceRange Range = S->getSourceRange(); 71 std::string Msg = Type; 72 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID, 73 &Msg, 1, &Range, 1); 74 } 75 76 /// WarnUnsupported - Print out a warning that codegen doesn't support the 77 /// specified decl yet. 78 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) { 79 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 80 "cannot codegen this %0 yet"); 81 std::string Msg = Type; 82 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID, 83 &Msg, 1); 84 } 85 86 /// setVisibility - Set the visibility for the given LLVM GlobalValue 87 /// according to the given clang AST visibility value. 88 void CodeGenModule::setVisibility(llvm::GlobalValue *GV, 89 VisibilityAttr::VisibilityTypes Vis) { 90 switch (Vis) { 91 default: assert(0 && "Unknown visibility!"); 92 case VisibilityAttr::DefaultVisibility: 93 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 94 break; 95 case VisibilityAttr::HiddenVisibility: 96 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 97 break; 98 case VisibilityAttr::ProtectedVisibility: 99 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 100 break; 101 } 102 } 103 104 /// AddGlobalCtor - Add a function to the list that will be called before 105 /// main() runs. 106 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) { 107 // TODO: Type coercion of void()* types. 108 GlobalCtors.push_back(Ctor); 109 } 110 111 /// EmitGlobalCtors - Generates the array of contsturctor functions to be 112 /// called on module load, if any have been registered with AddGlobalCtor. 113 void CodeGenModule::EmitGlobalCtors() { 114 if (GlobalCtors.empty()) return; 115 116 // Get the type of @llvm.global_ctors 117 std::vector<const llvm::Type*> CtorFields; 118 CtorFields.push_back(llvm::IntegerType::get(32)); 119 // Constructor function type 120 std::vector<const llvm::Type*> VoidArgs; 121 llvm::FunctionType* CtorFuncTy = 122 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false); 123 124 // i32, function type pair 125 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy); 126 llvm::StructType* CtorStructTy = 127 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL); 128 // Array of fields 129 llvm::ArrayType* GlobalCtorsTy = 130 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size()); 131 132 // Define the global variable 133 llvm::GlobalVariable *GlobalCtorsVal = 134 new llvm::GlobalVariable(GlobalCtorsTy, false, 135 llvm::GlobalValue::AppendingLinkage, 136 (llvm::Constant*)0, "llvm.global_ctors", 137 &TheModule); 138 139 // Populate the array 140 std::vector<llvm::Constant*> CtorValues; 141 llvm::Constant *MagicNumber = 142 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false); 143 std::vector<llvm::Constant*> StructValues; 144 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(), 145 E = GlobalCtors.end(); I != E; ++I) { 146 StructValues.clear(); 147 StructValues.push_back(MagicNumber); 148 StructValues.push_back(*I); 149 150 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues)); 151 } 152 153 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy, 154 CtorValues)); 155 } 156 157 158 159 void CodeGenModule::EmitAnnotations() { 160 if (Annotations.empty()) 161 return; 162 163 // Create a new global variable for the ConstantStruct in the Module. 164 llvm::Constant *Array = 165 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 166 Annotations.size()), 167 Annotations); 168 llvm::GlobalValue *gv = 169 new llvm::GlobalVariable(Array->getType(), false, 170 llvm::GlobalValue::AppendingLinkage, Array, 171 "llvm.global.annotations", &TheModule); 172 gv->setSection("llvm.metadata"); 173 } 174 175 /// ReplaceMapValuesWith - This is a really slow and bad function that 176 /// searches for any entries in GlobalDeclMap that point to OldVal, changing 177 /// them to point to NewVal. This is badbadbad, FIXME! 178 void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal, 179 llvm::Constant *NewVal) { 180 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator 181 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I) 182 if (I->second == OldVal) I->second = NewVal; 183 } 184 185 186 llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D, 187 bool isDefinition) { 188 // See if it is already in the map. If so, just return it. 189 llvm::Constant *&Entry = GlobalDeclMap[D]; 190 #if 0 191 // FIXME: The cache is currently broken! 192 if (Entry) return Entry; 193 #endif 194 195 const llvm::Type *Ty = getTypes().ConvertType(D->getType()); 196 197 // Check to see if the function already exists. 198 llvm::Function *F = getModule().getFunction(D->getName()); 199 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); 200 201 // If it doesn't already exist, just create and return an entry. 202 if (F == 0) { 203 // FIXME: param attributes for sext/zext etc. 204 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 205 D->getName(), &getModule()); 206 207 // Set the appropriate calling convention for the Function. 208 if (D->getAttr<FastCallAttr>()) 209 F->setCallingConv(llvm::CallingConv::Fast); 210 return Entry = F; 211 } 212 213 // If the pointer type matches, just return it. 214 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty); 215 if (PFTy == F->getType()) return Entry = F; 216 217 // If this isn't a definition, just return it casted to the right type. 218 if (!isDefinition) 219 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy); 220 221 // Otherwise, we have a definition after a prototype with the wrong type. 222 // F is the Function* for the one with the wrong type, we must make a new 223 // Function* and update everything that used F (a declaration) with the new 224 // Function* (which will be a definition). 225 // 226 // This happens if there is a prototype for a function (e.g. "int f()") and 227 // then a definition of a different type (e.g. "int f(int x)"). Start by 228 // making a new function of the correct type, RAUW, then steal the name. 229 llvm::Function *NewFn = llvm::Function::Create(FTy, 230 llvm::Function::ExternalLinkage, 231 "", &getModule()); 232 NewFn->takeName(F); 233 234 // Replace uses of F with the Function we will endow with a body. 235 llvm::Constant *NewPtrForOldDecl = 236 llvm::ConstantExpr::getBitCast(NewFn, F->getType()); 237 F->replaceAllUsesWith(NewPtrForOldDecl); 238 239 // FIXME: Update the globaldeclmap for the previous decl of this name. We 240 // really want a way to walk all of these, but we don't have it yet. This 241 // is incredibly slow! 242 ReplaceMapValuesWith(F, NewPtrForOldDecl); 243 244 // Ok, delete the old function now, which is dead. 245 assert(F->isDeclaration() && "Shouldn't replace non-declaration"); 246 F->eraseFromParent(); 247 248 // Return the new function which has the right type. 249 return Entry = NewFn; 250 } 251 252 static bool IsZeroElementArray(const llvm::Type *Ty) { 253 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty)) 254 return ATy->getNumElements() == 0; 255 return false; 256 } 257 258 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 259 bool isDefinition) { 260 assert(D->hasGlobalStorage() && "Not a global variable"); 261 262 // See if it is already in the map. 263 llvm::Constant *&Entry = GlobalDeclMap[D]; 264 if (Entry) return Entry; 265 266 QualType ASTTy = D->getType(); 267 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 268 269 // Check to see if the global already exists. 270 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true); 271 272 // If it doesn't already exist, just create and return an entry. 273 if (GV == 0) { 274 return Entry = new llvm::GlobalVariable(Ty, false, 275 llvm::GlobalValue::ExternalLinkage, 276 0, D->getName(), &getModule(), 0, 277 ASTTy.getAddressSpace()); 278 } 279 280 // If the pointer type matches, just return it. 281 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 282 if (PTy == GV->getType()) return Entry = GV; 283 284 // If this isn't a definition, just return it casted to the right type. 285 if (!isDefinition) 286 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy); 287 288 289 // Otherwise, we have a definition after a prototype with the wrong type. 290 // GV is the GlobalVariable* for the one with the wrong type, we must make a 291 /// new GlobalVariable* and update everything that used GV (a declaration) 292 // with the new GlobalVariable* (which will be a definition). 293 // 294 // This happens if there is a prototype for a global (e.g. "extern int x[];") 295 // and then a definition of a different type (e.g. "int x[10];"). Start by 296 // making a new global of the correct type, RAUW, then steal the name. 297 llvm::GlobalVariable *NewGV = 298 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage, 299 0, D->getName(), &getModule(), 0, 300 ASTTy.getAddressSpace()); 301 NewGV->takeName(GV); 302 303 // Replace uses of GV with the globalvalue we will endow with a body. 304 llvm::Constant *NewPtrForOldDecl = 305 llvm::ConstantExpr::getBitCast(NewGV, GV->getType()); 306 GV->replaceAllUsesWith(NewPtrForOldDecl); 307 308 // FIXME: Update the globaldeclmap for the previous decl of this name. We 309 // really want a way to walk all of these, but we don't have it yet. This 310 // is incredibly slow! 311 ReplaceMapValuesWith(GV, NewPtrForOldDecl); 312 313 // Verify that GV was a declaration or something like x[] which turns into 314 // [0 x type]. 315 assert((GV->isDeclaration() || 316 IsZeroElementArray(GV->getType()->getElementType())) && 317 "Shouldn't replace non-declaration"); 318 319 // Ok, delete the old global now, which is dead. 320 GV->eraseFromParent(); 321 322 // Return the new global which has the right type. 323 return Entry = NewGV; 324 } 325 326 327 void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) { 328 // If this is not a prototype, emit the body. 329 if (OMD->getBody()) 330 CodeGenFunction(*this).GenerateObjCMethod(OMD); 331 } 332 333 void CodeGenModule::EmitFunction(const FunctionDecl *FD) { 334 // If this is not a prototype, emit the body. 335 if (!FD->isThisDeclarationADefinition()) 336 return; 337 338 // If the function is a static, defer code generation until later so we can 339 // easily omit unused statics. 340 if (FD->getStorageClass() != FunctionDecl::Static) { 341 CodeGenFunction(*this).GenerateCode(FD); 342 return; 343 } 344 345 // We need to check the Module here to see if GetAddrOfFunctionDecl() has 346 // already added this function to the Module because the address of the 347 // function's prototype was taken. If this is the case, call 348 // GetAddrOfFunctionDecl to insert the static FunctionDecl into the used 349 // GlobalDeclsMap, so that EmitStatics will generate code for it later. 350 // 351 // Example: 352 // static int foo(); 353 // int bar() { return foo(); } 354 // static int foo() { return 5; } 355 if (getModule().getFunction(FD->getName())) 356 GetAddrOfFunctionDecl(FD, true); 357 358 StaticDecls.push_back(FD); 359 } 360 361 void CodeGenModule::EmitStatics() { 362 // Emit code for each used static decl encountered. Since a previously unused 363 // static decl may become used during the generation of code for a static 364 // function, iterate until no changes are made. 365 bool Changed; 366 do { 367 Changed = false; 368 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) { 369 // Check the map of used decls for our static. If not found, continue. 370 const Decl *D = StaticDecls[i]; 371 if (!GlobalDeclMap.count(D)) 372 continue; 373 374 // If this is a function decl, generate code for the static function if it 375 // has a body. Otherwise, we must have a var decl for a static global 376 // variable. 377 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 378 if (FD->getBody()) 379 CodeGenFunction(*this).GenerateCode(FD); 380 } else { 381 EmitGlobalVarInit(cast<VarDecl>(D)); 382 } 383 // Erase the used decl from the list. 384 StaticDecls[i] = StaticDecls.back(); 385 StaticDecls.pop_back(); 386 --i; 387 --e; 388 389 // Remember that we made a change. 390 Changed = true; 391 } 392 } while (Changed); 393 } 394 395 llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) { 396 return EmitConstantExpr(Expr); 397 } 398 399 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 400 /// annotation information for a given GlobalValue. The annotation struct is 401 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 402 /// GlobalValue being annotated. The second filed is thee constant string 403 /// created from the AnnotateAttr's annotation. The third field is a constant 404 /// string containing the name of the translation unit. The fourth field is 405 /// the line number in the file of the annotated value declaration. 406 /// 407 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 408 /// appears to. 409 /// 410 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 411 const AnnotateAttr *AA, 412 unsigned LineNo) { 413 llvm::Module *M = &getModule(); 414 415 // get [N x i8] constants for the annotation string, and the filename string 416 // which are the 2nd and 3rd elements of the global annotation structure. 417 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 418 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true); 419 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(), 420 true); 421 422 // Get the two global values corresponding to the ConstantArrays we just 423 // created to hold the bytes of the strings. 424 llvm::GlobalValue *annoGV = 425 new llvm::GlobalVariable(anno->getType(), false, 426 llvm::GlobalValue::InternalLinkage, anno, 427 GV->getName() + ".str", M); 428 // translation unit name string, emitted into the llvm.metadata section. 429 llvm::GlobalValue *unitGV = 430 new llvm::GlobalVariable(unit->getType(), false, 431 llvm::GlobalValue::InternalLinkage, unit, ".str", M); 432 433 // Create the ConstantStruct that is the global annotion. 434 llvm::Constant *Fields[4] = { 435 llvm::ConstantExpr::getBitCast(GV, SBP), 436 llvm::ConstantExpr::getBitCast(annoGV, SBP), 437 llvm::ConstantExpr::getBitCast(unitGV, SBP), 438 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo) 439 }; 440 return llvm::ConstantStruct::get(Fields, 4, false); 441 } 442 443 void CodeGenModule::EmitGlobalVar(const VarDecl *D) { 444 // If the VarDecl is a static, defer code generation until later so we can 445 // easily omit unused statics. 446 if (D->getStorageClass() == VarDecl::Static) { 447 StaticDecls.push_back(D); 448 return; 449 } 450 451 // If this is just a forward declaration of the variable, don't emit it now, 452 // allow it to be emitted lazily on its first use. 453 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0) 454 return; 455 456 EmitGlobalVarInit(D); 457 } 458 459 void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) { 460 // Get the global, forcing it to be a direct reference. 461 llvm::GlobalVariable *GV = 462 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true)); 463 464 // Convert the initializer, or use zero if appropriate. 465 llvm::Constant *Init = 0; 466 if (D->getInit() == 0) { 467 Init = llvm::Constant::getNullValue(GV->getType()->getElementType()); 468 } else if (D->getType()->isIntegerType()) { 469 llvm::APSInt Value(static_cast<uint32_t>( 470 getContext().getTypeSize(D->getInit()->getType()))); 471 if (D->getInit()->isIntegerConstantExpr(Value, Context)) 472 Init = llvm::ConstantInt::get(Value); 473 } 474 475 if (!Init) 476 Init = EmitGlobalInit(D->getInit()); 477 478 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 479 SourceManager &SM = Context.getSourceManager(); 480 AddAnnotation(EmitAnnotateAttr(GV, AA, 481 SM.getLogicalLineNumber(D->getLocation()))); 482 } 483 484 assert(GV->getType()->getElementType() == Init->getType() && 485 "Initializer codegen type mismatch!"); 486 GV->setInitializer(Init); 487 488 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 489 setVisibility(GV, attr->getVisibility()); 490 // FIXME: else handle -fvisibility 491 492 // Set the llvm linkage type as appropriate. 493 if (D->getStorageClass() == VarDecl::Static) 494 GV->setLinkage(llvm::Function::InternalLinkage); 495 else if (D->getAttr<DLLImportAttr>()) 496 GV->setLinkage(llvm::Function::DLLImportLinkage); 497 else if (D->getAttr<DLLExportAttr>()) 498 GV->setLinkage(llvm::Function::DLLExportLinkage); 499 else if (D->getAttr<WeakAttr>()) 500 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 501 else { 502 // FIXME: This isn't right. This should handle common linkage and other 503 // stuff. 504 switch (D->getStorageClass()) { 505 case VarDecl::Static: assert(0 && "This case handled above"); 506 case VarDecl::Auto: 507 case VarDecl::Register: 508 assert(0 && "Can't have auto or register globals"); 509 case VarDecl::None: 510 if (!D->getInit()) 511 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 512 break; 513 case VarDecl::Extern: 514 case VarDecl::PrivateExtern: 515 // todo: common 516 break; 517 } 518 } 519 } 520 521 /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified 522 /// declarator chain. 523 void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) { 524 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator())) 525 if (D->isFileVarDecl()) 526 EmitGlobalVar(D); 527 } 528 529 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 530 // Make sure that this type is translated. 531 Types.UpdateCompletedType(TD); 532 } 533 534 535 /// getBuiltinLibFunction 536 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 537 if (BuiltinID > BuiltinFunctions.size()) 538 BuiltinFunctions.resize(BuiltinID); 539 540 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 541 // a slot for it. 542 assert(BuiltinID && "Invalid Builtin ID"); 543 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 544 if (FunctionSlot) 545 return FunctionSlot; 546 547 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn"); 548 549 // Get the name, skip over the __builtin_ prefix. 550 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10; 551 552 // Get the type for the builtin. 553 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context); 554 const llvm::FunctionType *Ty = 555 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 556 557 // FIXME: This has a serious problem with code like this: 558 // void abs() {} 559 // ... __builtin_abs(x); 560 // The two versions of abs will collide. The fix is for the builtin to win, 561 // and for the existing one to be turned into a constantexpr cast of the 562 // builtin. In the case where the existing one is a static function, it 563 // should just be renamed. 564 if (llvm::Function *Existing = getModule().getFunction(Name)) { 565 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 566 return FunctionSlot = Existing; 567 assert(Existing == 0 && "FIXME: Name collision"); 568 } 569 570 // FIXME: param attributes for sext/zext etc. 571 return FunctionSlot = 572 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name, 573 &getModule()); 574 } 575 576 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 577 unsigned NumTys) { 578 return llvm::Intrinsic::getDeclaration(&getModule(), 579 (llvm::Intrinsic::ID)IID, Tys, NumTys); 580 } 581 582 llvm::Function *CodeGenModule::getMemCpyFn() { 583 if (MemCpyFn) return MemCpyFn; 584 llvm::Intrinsic::ID IID; 585 switch (Context.Target.getPointerWidth(0)) { 586 default: assert(0 && "Unknown ptr width"); 587 case 32: IID = llvm::Intrinsic::memcpy_i32; break; 588 case 64: IID = llvm::Intrinsic::memcpy_i64; break; 589 } 590 return MemCpyFn = getIntrinsic(IID); 591 } 592 593 llvm::Function *CodeGenModule::getMemMoveFn() { 594 if (MemMoveFn) return MemMoveFn; 595 llvm::Intrinsic::ID IID; 596 switch (Context.Target.getPointerWidth(0)) { 597 default: assert(0 && "Unknown ptr width"); 598 case 32: IID = llvm::Intrinsic::memmove_i32; break; 599 case 64: IID = llvm::Intrinsic::memmove_i64; break; 600 } 601 return MemMoveFn = getIntrinsic(IID); 602 } 603 604 llvm::Function *CodeGenModule::getMemSetFn() { 605 if (MemSetFn) return MemSetFn; 606 llvm::Intrinsic::ID IID; 607 switch (Context.Target.getPointerWidth(0)) { 608 default: assert(0 && "Unknown ptr width"); 609 case 32: IID = llvm::Intrinsic::memset_i32; break; 610 case 64: IID = llvm::Intrinsic::memset_i64; break; 611 } 612 return MemSetFn = getIntrinsic(IID); 613 } 614 615 llvm::Constant *CodeGenModule:: 616 GetAddrOfConstantCFString(const std::string &str) { 617 llvm::StringMapEntry<llvm::Constant *> &Entry = 618 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 619 620 if (Entry.getValue()) 621 return Entry.getValue(); 622 623 std::vector<llvm::Constant*> Fields; 624 625 if (!CFConstantStringClassRef) { 626 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 627 Ty = llvm::ArrayType::get(Ty, 0); 628 629 CFConstantStringClassRef = 630 new llvm::GlobalVariable(Ty, false, 631 llvm::GlobalVariable::ExternalLinkage, 0, 632 "__CFConstantStringClassReference", 633 &getModule()); 634 } 635 636 // Class pointer. 637 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 638 llvm::Constant *Zeros[] = { Zero, Zero }; 639 llvm::Constant *C = 640 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2); 641 Fields.push_back(C); 642 643 // Flags. 644 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 645 Fields.push_back(llvm::ConstantInt::get(Ty, 1992)); 646 647 // String pointer. 648 C = llvm::ConstantArray::get(str); 649 C = new llvm::GlobalVariable(C->getType(), true, 650 llvm::GlobalValue::InternalLinkage, 651 C, ".str", &getModule()); 652 653 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); 654 Fields.push_back(C); 655 656 // String length. 657 Ty = getTypes().ConvertType(getContext().LongTy); 658 Fields.push_back(llvm::ConstantInt::get(Ty, str.length())); 659 660 // The struct. 661 Ty = getTypes().ConvertType(getContext().getCFConstantStringType()); 662 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields); 663 llvm::GlobalVariable *GV = 664 new llvm::GlobalVariable(C->getType(), true, 665 llvm::GlobalVariable::InternalLinkage, 666 C, "", &getModule()); 667 GV->setSection("__DATA,__cfstring"); 668 Entry.setValue(GV); 669 return GV; 670 } 671 672 /// GenerateWritableString -- Creates storage for a string literal. 673 static llvm::Constant *GenerateStringLiteral(const std::string &str, 674 bool constant, 675 CodeGenModule &CGM) { 676 // Create Constant for this string literal 677 llvm::Constant *C=llvm::ConstantArray::get(str); 678 679 // Create a global variable for this string 680 C = new llvm::GlobalVariable(C->getType(), constant, 681 llvm::GlobalValue::InternalLinkage, 682 C, ".str", &CGM.getModule()); 683 return C; 684 } 685 686 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character 687 /// array containing the literal. The result is pointer to array type. 688 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) { 689 // Don't share any string literals if writable-strings is turned on. 690 if (Features.WritableStrings) 691 return GenerateStringLiteral(str, false, *this); 692 693 llvm::StringMapEntry<llvm::Constant *> &Entry = 694 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 695 696 if (Entry.getValue()) 697 return Entry.getValue(); 698 699 // Create a global variable for this. 700 llvm::Constant *C = GenerateStringLiteral(str, true, *this); 701 Entry.setValue(C); 702 return C; 703 } 704